学习内容:
(一)字典
字典(也叫 dict)是一种和列表类似的数据存储方式。但是不同于列表只能用数字获取数据,字典可以用任何东西来获取。
读数据:
字典能够把一个东西和另一个东西关联起来,不管它们是什么类型。
stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}
print(stuff['name']) # Zed
print(stuff['age']) # 39
print(stuff['height']) # 74
stuff['city'] = "SF"
print(stuff['city'])
print(stuff) # {'name': 'Zed', 'age': 39, 'height': 74, 'city': 'SF'}
写入数据
stuff[1] = "Wow"
stuff[2] = "Neato"
print(stuff[1]) # Wow
print(stuff[2]) # Neato
print(stuff)
# {'name': 'Zed', 'age': 39, 'height': 74, 'city': 'SF', 1: 'Wow', 2: 'Neato'}
删除数据
del stuff['city']
print(stuff) # {'name': 'Zed', 'age': 39, 'height': 74, 1: 'Wow', 2: 'Neato'}
例子:
- 字典取数据时可以嵌套,如:cities[states[‘Michigan’]]
- 用for…in…遍历字典的每一个元素,states.items代表每一项 ,state代表第一个字符,abbrev代表第二个字符
- 在字典里查找数据可以用get,第一个参数是名称,第二个参数是没有找到的返回值,cities.get(‘TX’, ‘Does Not Exist’) #如果在city里没有找到 TX ,就返回’Does Not Exist’
##############一个字典实例###############
# create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
print(cities)
#{'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville', 'NY': 'New York', 'OR': 'Portland'}
# print out some cities
print('-' * 10)
print("NY State has: ", cities['NY'])
print("OR State has: ", cities['OR'])
# NY State has: New York
# OR State has: Portland
# print some states
print('-' * 10)
print("Michigan's abbreviation is: ", states['Michigan'])
print("Florida's abbreviation is: ", states['Florida'])
# Michigan's abbreviation is: MI
# Florida's abbreviation is: FL
# do it by using the state then cities dict
print('-' * 10)
print("Michigan has: ", cities[states['Michigan']])
print("Florida has: ", cities[states['Florida']])
# Michigan has: Detroit
# Florida has: Jacksonville
# print every state abbreviation
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} is abbreviated {abbrev}")
# 用for...in...遍历字典的每一个元素,states.items代表每一项 ,state代表第一个字符,abbrev代表第二个字符
# Oregon is abbreviated OR
# Florida is abbreviated FL
# California is abbreviated CA
# New York is abbreviated NY
# Michigan is abbreviated MI
# print every city in state
print('-' * 10)
for abbrev, city in list(cities.items()):
print(f"{abbrev} has the city {city}")
# now do both at the same time
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} state is abbreviated {abbrev}")
print(f"and has city {cities[abbrev]}")
print('-' * 10)
# safely get a abbreviation by state that might not be there
state = states.get('Texas')
if not state:
print("Sorry, no Texas.")
# get a city with a default value
city = cities.get('TX', 'Does Not Exist') #如果在city里没有找到 TX ,就返回'Does Not Exist'
print(f"The city for the state 'TX' is: {city}")
# The city for the state 'TX' is: Does Not Exist
(二)元组
元组是另一个数据类型,类似于 List(列表)。
元组用 () 标识。内部元素用逗号隔开。但是元组不能二次赋值,相当于只读列表。
tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print(tuple) # 输出完整元组
print(tuple[0]) # 输出元组的第一个元素
print(tuple[1:3]) # 输出第二个至第四个(不包含)的元素
print(tuple[2:]) # 输出从第三个开始至列表末尾的所有元素
print(tinytuple * 2) # 输出元组两次
print(tuple + tinytuple) # 打印组合的元组
输出如下:
以下是元组无效的,因为元组是不允许更新的
tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 )
tuple[2] = 1000 # 元组中是非法应用
(三)布尔类型
and :有一个为假,结果就为假
or: 有一个为真,结果才为真
True and True # True
False and True # False
1 == 1 and 2 == 1 # False
"test" == "test" # True
1 == 1 or 2 != 1 # True
True and 1 == 1 # True
False and 0 != 0 # False
not ("testing" == "testing" and "Zed" == "Cool Guy") # True
1 == 1 and (not ("testing" == 1 or 1 == 0)) # True
"chunky" == "bacon" and (not (3 == 4 or 3 == 3)) # False
3 == 3 and (not ("testing" == "testing" or "Python" == "Fun")) #False
Process finished with exit code 0
(四)读写文件
close - 关闭文件,就像编辑器中的 “文件->另存为”一样。
read - 读取文件内容。你可以把读取结果赋给一个变量。
readline - 只读取文本文件的一行内容。
truncate - 清空文件。清空的时候要当心。
write(‘stuff’) - 给文件写入一些“东西”。
seek(0) - 把读/写的位置移到文件最开头。
1.open
使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
file_object = open(‘thefile.txt’)
2.读文件
读文本文件
input = open(‘data’, ‘r’)
#第二个参数默认为r
input = open(‘data’)
3.写文件
写文本文件
output = open(‘data’, ‘w’)
写二进制文件
output = open(‘data’, ‘wb’)
追加写文件
output = open(‘data’, ‘w+’)
写数据
file_object = open(‘thefile.txt’, ‘w’)
file_object.write(all_the_text)
file_object.close( )
总结:
task03:本次学习了字典、元组、布尔类型和文件操作,重要的是对字典的遍历;元组只能读不能写;and是有一个为假,结果就为假,or是有一个为真,结果才为真;最后是读写文件的一些操作,之后都会用到。