1.字典
定义
Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
创建
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
d['Michael'] # 输出95
d = {}
方法
1.clear
clear删除所有字典项,无返回值
d.clear()
2.copy
copy返回一个新字典,浅复制
y = x.copy()
3.get
get获取字典键值,当访问不存在的键时,返回None
d.get['name']
4.items
items返回一个包含所有字典项的列表,其中每个元素形式为(key,value)
d.items()
5.keys
keys返回一个字典视图
6.pop
pop获取与指定键相关的值,并删除该键值对
d.pop('x')
7.values
values返回一个由字典中的值组成的字典视图
2.集合
定义
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
创建
s = set([1,2,3])
s = set()
方法
1.add
add将元素加入集合中
s.add('a')
2.update
update更新多个值
s.update([1,2,3])
3.remove
remove移除集合中元素,若移除元素不在集合中报错
s.remove('cc')
4.discard
discard移除集合中元素,不在集合中不会报错
s.discard('cc')
5.pop
pop随机移除一个元素
s.pop()
6.clear
clear清空集合
s.clear()
7.len
计算set元素个数
len(s)
8.copy
复制集合
s2=s1.copy()
3.条件判断
if <条件判断1>:
<执行1>
elif <条件判断2>:
<执行2>
elif <条件判断3>:
<执行3>
else:
<执行4>
# 三目运算符
条件为真时的结果 if 判段的条件 else 条件为假时的结果
4.循环
# for loop
for line in lines:
print(line)
for i in range(len(lines)):
print(lines[i])
# while
while True:
line = file.readline()
if not line:
break
else:
...
5.参考资料
https://www.liaoxuefeng.com/
http://www.runoob.com/