tuple、dict和set注意要点和常用操作
tuple
tuple是可以理解成一个不变的list,注意的是当tuple中有list的话,list是可以变的。
list1 = [1, 2]
t = ('a', 2, list1)
print(id(list1)) # 3101965286144
list1[1] = 3
print(id(list1)) # 3101965286144
无论list怎么变,它的地址是变的,所有tuple并没有变。
dict常见操作
创建dict
empty_dict = {}
dict1 = {'a': 1, 'b': 2}
dict2 = dict(zip(['a', 'b'], [1, 2]))
dict3 = dict([('a', 1),('b', 2)])
dict4 = dict(a = 1, b = 2)
常见操作
一、判断key是否在dict中
print('c' in dict1) # False
print(dict1.get('a')) # get 到了反回value
print(dict1.get('c')) # get 不到反回None
print(dict1.get('c', -1)) # get 不到反回-1
二、操作dict
clear()
print(dict1.clear()) # {}
update() key存在即更新value,key不存在增加一对key-value
print(dict2.update({'a': 10, 'c': 3}) # {'a': 10, 'b': 2, 'c': 3}
items() 获取字典中的所有 key-value 对
print(dict3.items()) # dict_items([('a', 1), ('b', 2)])
key() 获取所有key
print(dict3.keys()) # dict_keys(['a', 'b'])
values() 获取所有value
print(dict3.values()) # dict_values([1, 2])
pop() 获取指定 key 对应的 value,并删除这个 key-value 对。
print(dict3.pop('a') # 1
print(dict3) # {'b': 2}
popitem() 删除最后一个key-value()
print(dict4.popitem() # {'b': 2}
setdefault() 如果key存在,不会修改dict的内容,如果不存在即增加key-value
print(dict3.setdefault('d', 4))
print(dict3) # {'a': 1, 'b': 2, 'd': 4}
print(dict3.setdefault('a', 10)
print(dict3) # {'a':1, 'b':2, 'c': 3}
使用字典格式化字符串
字符串模板中使用key
temp = '教程是:%(name)s, 价格是:%(price)010.2f, 出版社是:%(publish)s'
book = {'name':'Python基础教程', 'price': 99, 'publish': 'C语言中文网'}
# 使用字典为字符串模板中的key传入值
print(temp % book)
book = {'name':'C语言小白变怪兽', 'price':159, 'publish': 'C语言中文网'}
# 使用字典为字符串模板中的key传入值
print(temp % book)
# 教程是:Python基础教程, 价格是:0000099.00, 出版社是:C语言中文网
# 教程是:C语言小白变怪兽, 价格是:0000159.00, 出版社是:C语言中文网
set
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
要创建一个set,需要提供一个list作为输入集合
s = set([1, 2, 3])
add(key)
remove(key)
set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作
s2 = set([2, 3, 4])
print(s1 & s2) # {2, 3}
print(s1 | s2) # {1, 2, 3, 4}
参考:
Python字典及基本操作(超级详细)http://c.biancheng.net/view/2212.html
https://www.liaoxuefeng.com/wiki/1016959663602400/1017104324028448
浙公网安备 33010602011771号