python入门基础知识四(字典与集合)
字典
形式
dict_name = {key1:value1,key2,value2,...}
空字典:dict_name = {} or dict_name = dict()
字典的相关操作
增:
dict_name[key] = value, 若键存在则修改对应的值,若键不存在则在尾部创建键值对。
a = {'chicken':7.5,'pork':20,'beef':45} a['beef'] = 50 print(a) {'chicken': 7.5, 'pork': 20, 'beef': 50} a['mutton'] = 40 print(a) {'chicken': 7.5, 'pork': 20, 'beef': 50, 'mutton': 40}
删:
del dict_name[key] # 明示键名,程序会自动删除键值对
print(a) {'chicken': 7.5, 'pork': 20, 'beef': 50, 'mutton': 40} del a['pork'] print(a) {'chicken': 7.5, 'beef': 50, 'mutton': 40}
del dict_name # 删除整个字典
dict_name.clear() # 清空字典
查:用键查值,不能用值查键,键是唯一的而值不一定是唯一的。
print(dict_name[key])
print(a) {'chicken': 7.5, 'beef': 50, 'mutton': 40} print(a['beef']) 50
dict_name.get(key, return value)
print(a) {'chicken': 7.5, 'beef': 50, 'mutton': 40, 'pork': 20} print(a.get('fish')) None print(a.get('fish','you dumb ass')) you dumb ass a.get('fish') # 返回空值
dict_name.values() # 返回字典中所有的值
dict_name.items() # 以键值对的方式返回值
print(a) {'chicken': 7.5, 'beef': 50, 'mutton': 40, 'pork': 20} print(a.values()) dict_values([7.5, 50, 40, 20]) print(a.items()) dict_items([('chicken', 7.5), ('beef', 50), ('mutton', 40), ('pork', 20)]) a.values() dict_values([7.5, 50, 40, 20]) a.items() dict_items([('chicken', 7.5), ('beef', 50), ('mutton', 40), ('pork', 20)])
字典的循环遍历
1. 遍历字典的key
for i in dict_name.keys():
print(i)
2. 遍历字典的value
for i in dict_name.values():
print(i)
3. 遍历字典的元素
for i in dict_name.items():
print(i)
4. 遍历字典的键值
for i,j in dict_name.items():
print(f'{i} = {j}')
a = {'beef':45,'mutton':35,'pork':22} for i in a: ... print(i) ... beef mutton pork
for i in a.keys(): ... print(i) ... beef mutton pork
for i in a.values(): ... print(i) ... 45 35 22 for i in a.items(): ... print(i) ... ('beef', 45) ('mutton', 35) ('pork', 22)
for i,j in a.items(): ... print(f'{i} = {j}') ... beef = 45 mutton = 35 pork = 22
集合
形式
set_name = {value1,value2,value3,...}
空集合 set_name = set() # 如果用{}创建的是空字典
集合的特性:自动去除重复数据,不支持下标
集合的操作
增:set_name.add(value) # 增加一个数据
set_name.update(数据序列) # 数据序列:列表,字符串,元组
删:set_name.remove(value) # only one value will be accepted, if value is no exist, show error message
set_name.discard(value) # no message will be shown
set_name.pop() # delete values from letf to right, one at a time, show the deleted value
b = {1, 2, 6, 9} b.pop() 1 b.pop() 2 b.pop() 6 b.pop() 9 b.update(1,3,4,5,7) Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: 'int' object is not iterable b.update([1,3,4,5,7]) # 注意update支持的类型:列表,字符串,元组 print(b) {1, 3, 4, 5, 7} c = b.pop() print(c) 1 b.update((1,3,4,5,7,9)) print(b) {3, 4, 5, 7, 1, 9}
查:print(value in set_name) # 返回true or false
print(value not in set_name) # 返回true or false
已知的五种类型转换
int() float() str()
list(序列名) # 将序列转换为列表
tuple(序列名) # 将序列转换为元组
set(序列名) # 将序列转换成集合
总结
序列是一个存放多个值的连续内存空间
有序序列:意味着有下标,可以进行下标、切片等操作的序列。如,列表、元组、字符串
无序序列:字典、集合
可变序列:元素进行增删改后,内存地址不变。若内存地址改变就是不可变序列
可变类型:列表、字典、集合……
不可变类型:整型、浮点型、字符串、元组……