在字典操作中有一种常见的操作就是items,小笔记走一下
先创建一个散列表(字典),每个key对应的value都是一个集合(使用set()实现)
stations = {} stations["kone"] = set(["id","nv","ut"]) stations["ktwo"] = set(["wd","id","mt"]) stations["kthree"] = set(["or","nv","ca"]) stations["kfour"] = set(["nv","ut"]) stations["kfive"] = set(["ca","az"]) print(stations)
{'kfive': {'az', 'ca'},
'kfour': {'nv', 'ut'},
'kone': {'id', 'nv', 'ut'},
'kthree': {'ca', 'nv', 'or'},
'ktwo': {'id', 'mt', 'wd'}}
使用items看一下输出结构:
stations.items() Out[23]: dict_items([('kthree', {'nv', 'ca', 'or'}), ('ktwo', {'wd', 'mt', 'id'}), ('kone', {'ut', 'id', 'nv'}), ('kfour', {'ut', 'nv'}), ('kfive', {'ca', 'az'})])
可以看到items把字典的每一对key和value组成数组后以列表的形式返回。
keys = [] values = [] for key, value in stations.items(): keys.append(key) values.append(value) print("keys:\n",keys) print("values:\n",values)
keys:
['kfive', 'kone', 'ktwo', 'kthree', 'kfour']
values:
[{'ca', 'az'}, {'id', 'ut', 'nv'}, {'id', 'wd', 'mt'}, {'ca', 'or', 'nv'}, {'ut', 'nv'}]
当然也可以利用for循环分别获取keys值和values值,就相当于dict.keys()和dict_values()方法
注意字典不支持index操作,比如:
stations.items()[0]
会报错:TypeError: 'dict_items' object does not support indexing
python中,利用"&"求交集,"|"求并集,"-"求差集(补集)
a = set([1,3,5,7,9])
print(a)
Out[1]: {1, 3, 5, 7, 9}
b = set([1,2,3,4,5])
a&b
Out[2]: {1, 3, 5}
a|b
Out[3]: {1, 2, 3, 4, 5, 7, 9}
a-c
Out[4]: {7, 9}
python中,利用"add"h和"remove"对集合的元素进行增删操作
a.add(2)
print(a)
Out[64]: {1, 2, 3, 5, 7, 9}
a.remove(9)
print(a)
Out[66]: {1, 2, 3, 5, 7}
提醒:使用add和remove对集合元素进行增删操作只能传入一个元素,如果传入多个会报错如下:
TypeError: add() takes exactly one argument (4 given)