- with as
with as可以用来避免读取文件之后忘记关掉的问题
with open("/tmp/foo.txt") as file:
data = file.read()
# 我们可以不用自己手动close(),它会在自己执行完with后的代码块之后自动关闭
- 列表(list)
列表的数据项不需要具有相同的类型
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
访问列表中的值
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
添加元素
list = [] ## 空列表
list.append('Google') ## 使用 append() 添加元素
list.append('Runoob')
删除元素
del list1[2]
列表可以转换为tuple
tuple也可以转换为列表
tuple的不同之处在于不可以修改数据
- 字典(Dictionary)
http://www.runoob.com/python/python-dictionary.html
字典是一种可变容器,可以存储任意类型对象
字典的每个键值key=>value,每个键值对之间用逗号分割,整个字典包括在花括号里面
d = {key1 : value1, key2 : value2 }
键一般是唯一的,如果重复最后的一个键值对会替换前面的,值不需要唯一
可以利用字典的键值进行访问
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
修改字典元素
dict['Age'] = 8 # 更新
dict['School'] = "RUNOOB" # 添加
删除字典元素
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # 删除键是'Name'的条目
dict.clear() # 清空词典所有条目
del dict # 删除词典