# 集合运算
## 并集
1、将两个集合A和B的所有元素合并到一起,组成的集合称作集合A与集合B的并集
union(*others)
返回和多个集合合并后的新的集合
|: 运算符重载
等同union
In [6]: s1 = {1,2,3,4}
In [7]: s2 = {1,4,5,6}
In [8]: s1 |s2
Out[8]: {1, 2, 3, 4, 5, 6}
In [9]: s1.union(s2)
Out[9]: {1, 2, 3, 4, 5, 6}
update(*others)
和多个集合合并,就地修改
|=:
等同于update
In [10]: s1 |= s2
In [11]: s1
Out[11]: {1, 2, 3, 4, 5, 6}
## 交集
1、集合A和B,由所有属于A且属于B的元素组成的集合
intersction(*others)
返回多个集合的交集
&:
等同于intersection
In [12]: s1 & s2
Out[12]: {1, 4, 5, 6}
In [13]: s1
Out[13]: {1, 2, 3, 4, 5, 6}
In [14]: s2
Out[14]: {1, 4, 5, 6}
intersection_update(*others)
获取和多个集合的交集,并就地修改
&=:
等同于intersection_update
In [18]: s1 &= s2
In [19]: s1
Out[19]: {1, 4, 5, 6}
In [20]: s2
Out[20]: {1, 4, 5, 6}
## 差集
集合A和B,由所有属于A且不属于B的元素组成的集合
difference(*others)
返回多个集合的差集
-:
等同于difference
In [21]: s1 = {1, 2, 3, 4, 5, 6}
In [22]: s2
Out[22]: {1, 4, 5, 6}
In [23]: s1 – s2
Out[23]: {2, 3}
difference_update(*others)
获取和多个集合的差集并就地修改
-=:
等同于difference_update
In [24]: s1
Out[24]: {1, 2, 3, 4, 5, 6}
In [25]: s2
Out[25]: {1, 4, 5, 6}
In [27]: s1 -= s2
In [28]: s1
Out[28]: {2, 3}
In [29]: s2
Out[29]: {1, 4, 5, 6}
## 对称差集
集合A和B,由所有不属于A和B的交集元素组成的集合,记作(A-B)u(B-A)
symmetric_differece(other)
返回和另一个集合的差集
^:
等同于symmetric_differece
In [1]: s1 = {1,2,3,4,5,6}
In [2]: s2 = {5,6,7,8,9}
In [3]: s1 ^ s2
Out[3]: {1, 2, 3, 4, 7, 8, 9}
symmetric_differece_update(other)
获取和另一个集合的差集并就地修改
^=:
等同于symmetric_differece_update
In [3]: s1
Out[3]: {1, 2, 3, 4, 5, 6}
In [4]: s2
Out[4]: {4, 5, 6, 7, 8, 9}
In [5]: s1 ^= s2
In [6]: s1
Out[6]: {1, 2, 3, 7, 8, 9}
issubset(other),<=
判断当前集合是否是另一个集合的子集
set1 < set2
判断set1是否是set2的真子集
issuperset(other)、>=
判断当前集合是否是other的超集
isdisjoint(other)
当前集合和另一个集合没有交集
没有交集返回Tru
# dict字典
### 字典
1、key-value键值对的数据的集合
2、可变的、无序的、key不重复
Question:键值对的含义和概念?
### 字典dict定义 初始化
1、d = dict()或者 d = {},后者为常用
2、dict(**kwargs)使用可迭代对象和name=value对构造字典,不过可以迭代对象的元素必须为一个二元结构
model:
d = dict(((1,’a’),(2,’b’)))
In [260]: d
Out[260]: {1: ‘a’, 2: ‘b’}
或者d = dict(([1,’a’],[2,’b’]))
In [261]: d = dict(([1,’a’],[2,’b’]))
In [262]: d
Out[262]: {1: ‘a’, 2: ‘b’}
3、dict(mapping,**kwarg)使用一个字典构建另一个字典
4、d = {‘a’:10,’b’:20,’c’:None,’d’:[1,2,3]}
5、类方法dict.fromkeys(iterable,value)
d = dict.fromkeys(range(5))
d = dict.fromkeys(range(5),0)
model:
In [263]: d = dict.fromkeys(range(5))
In [264]: d
Out[264]: {0: None, 1: None, 2: None, 3: None, 4: None}
In [265]: d = dict.fromkeys(range(5),0)
In [266]: d
Out[266]: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}
备注:4的方法比较常用,需多加熟悉和练习
一些其它的例子:
In [267]: d = dict(a=5,b=6,z=[1,2,3])
In [268]: d
Out[268]: {‘a’: 5, ‘b’: 6, ‘z’: [1, 2, 3]}
In [269]: d = dict(a=5,b=6,z=[123])
In [270]: d
Out[270]: {‘a’: 5, ‘b’: 6, ‘z’: [123]}
In [271]: l1 = list(range(5))
In [272]: l1
Out[272]: [0, 1, 2, 3, 4]
In [273]: d = dict(enumerate(l1))
In [274]: d
Out[274]: {0: 0, 1: 1, 2: 2, 3: 3, 4: 4} #返回的都是二元组
In [275]: e = enumerate(l1)
In [276]: e
Out[276]: <enumerate at 0x7f20aefa0048>
In [277]: type(e)
Out[277]: enumerate
In [278]: d = dict(e)
In [279]: d
Out[279]: {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
In [1]: d1 = dict.fromkeys(range(1,11))
In [2]: d2 = dict.fromkeys(range(1,11),[1,2])
In [3]: d3 = dict.fromkeys(range(1,11),1)
In [4]: d4 = dict.fromkeys(range(1,11),[1])
In [5]: d1
Out[5]:
{1: None,
2: None,
3: None,
4: None,
5: None,
6: None,
7: None,
8: None,
9: None,
10: None}
In [6]: d2
Out[6]:
{1: [1, 2],
2: [1, 2],
3: [1, 2],
4: [1, 2],
5: [1, 2],
6: [1, 2],
7: [1, 2],
8: [1, 2],
9: [1, 2],
10: [1, 2]}
In [7]: d3
Out[7]: {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1}
In [8]: d4
Out[8]:
{1: [1],
2: [1],
3: [1],
4: [1],
5: [1],
6: [1],
7: [1],
8: [1],
9: [1],
10: [1]}
备注:千万不要使用d2[10].append(3)
展示如下:
In [13]: d2[10].append(3)
In [14]: d2
Out[14]:
{1: [1, 2, 3],
2: [1, 2, 3],
3: [1, 2, 3],
4: [1, 2, 3],
5: [1, 2, 3],
6: [1, 2, 3],
7: [1, 2, 3],
8: [1, 2, 3],
9: [1, 2, 3],
10: [1, 2, 3]}
### 字典元素的访问
1、d[key]
返回key对应的值value
key不存在抛出KeyError异常
In [18]: d3[1]
Out[18]: 1
2、get(key[,default])
返回key对应的值value
key不存在返回缺省值,如果没有设置缺省值就返回None
In [20]: d3.get(9)
Out[20]: 1
In [23]: s = d3.get(11)
In [24]: s
In [25]: type(s)
Out[25]: NoneType
由返回值就可以使用判断,if None或者if not None
3、setdefault(key[,default])
返回key对应的值value
key不存在,添加kv对,value为default,并返回default,如果default没有设置,缺省值为None
In [30]: d = dict(([(1,3,4),{1,3,5,6}],))
In [31]: d[(1,3,4)]
Out[31]: {1, 3, 5, 6}
In [32]: d.setdefault(‘a’,3)
Out[32]: 3
In [33]: d
Out[33]: {‘a’: 3, (1, 3, 4): {1, 3, 5, 6}}
In [37]: d[‘a’]
Out[37]: 3
In [38]: d
Out[38]: {‘a’: 3, (1, 3, 4): {1, 3, 5, 6}}
In [39]: d[‘a’] = 100
In [40]: d
Out[40]: {‘a’: 100, (1, 3, 4): {1, 3, 5, 6}}
### 字典增加和修改
d[key] = value
将key对应的值修改为value
key不存在添加新的kv对
In [44]: d
Out[44]: {‘a’: 100, (1, 3, 4): {1, 3, 5, 6}}
In [45]: d[‘a’]
Out[45]: 100
In [46]: d[‘b’] = 10
In [47]: d
Out[47]: {‘a’: 100, ‘b’: 10, (1, 3, 4): {1, 3, 5, 6}}
update([other]) -> None
使用另一个字典的kv对更新本字典
key不存在,就添加
key存在,覆盖已经存在的key对应的值
就地修改
In [48]: d
Out[48]: {‘a’: 100, ‘b’: 10, (1, 3, 4): {1, 3, 5, 6}}
In [49]: d1 = {‘c’:68}
In [50]: d.update(d1)
In [51]: d
Out[51]: {‘c’: 68, ‘a’: 100, ‘b’: 10, (1, 3, 4): {1, 3, 5, 6}}
In [51]: d
Out[51]: {‘c’: 68, ‘a’: 100, ‘b’: 10, (1, 3, 4): {1, 3, 5, 6}}
In [52]: d.update(f = 2)
In [53]: d
Out[53]: {‘f’: 2, ‘c’: 68, ‘a’: 100, ‘b’: 10, (1, 3, 4): {1, 3, 5, 6}}
In [53]: d
Out[53]: {‘f’: 2, ‘c’: 68, ‘a’: 100, ‘b’: 10, (1, 3, 4): {1, 3, 5, 6}}
In [54]: d.update(f = 5)
In [55]: d
Out[55]: {‘c’: 68, ‘a’: 100, (1, 3, 4): {1, 3, 5, 6}, ‘b’: 10, ‘f’: 5}
In [56]: d.update({‘x’:2})
In [57]: d
Out[57]: {‘c’: 68, ‘a’: 100, (1, 3, 4): {1, 3, 5, 6}, ‘x’: 2, ‘b’: 10, ‘f’: 5}
### 字典删除
pop(key[,default])
key存在,移除,返回其value
key不存在,返回给定的default
default未设置,key不存在,抛出KeyError异常
In [58]: d.pop(‘f’)
Out[58]: 5
In [59]: d
Out[59]: {‘c’: 68, ‘a’: 100, (1, 3, 4): {1, 3, 5, 6}, ‘x’: 2, ‘b’: 10}
popitem()
移除并返回一个任意的键值对
字典为empty,抛出KeyError异常
In [61]: d.popitem()
Out[61]: (‘c’, 68)
In [62]: d
Out[62]: {‘a’: 100, (1, 3, 4): {1, 3, 5, 6}, ‘x’: 2, ‘b’: 10}
clear()
清空字典
In [63]: d.clear()
In [64]: d
Out[64]: {}
### 字典删除
del语句
In [65]: a = True
In [66]: b = [6]
In [67]: d = {‘a’:1,’b’:b,’c’:[1,2,3]}
In [68]: del a
In [69]: d
Out[69]: {‘a’: 1, ‘b’: [6], ‘c’: [1, 2, 3]}
In [71]: del d[‘c’] #删除key,对应的value也就不存在了
In [72]: d
Out[72]: {‘a’: 1, ‘b’: [6]}
In [72]: d
Out[72]: {‘a’: 1, ‘b’: [6]}#删除b[0],删除b中索引为0的元素
In [73]: del b[0]
In [74]: d
Out[74]: {‘a’: 1, ‘b’: []}
In [76]: del c
In [77]: del b
In [78]: d
Out[78]: {‘a’: 1, ‘b’: []}
In [79]: b = d[‘b’]
In [80]: d
Out[80]: {‘a’: 1, ‘b’: []}
In [81]: b
Out[81]: []
备注:del a[‘c’]看着像删除了一个对象,本质上减少了一个对象的引用,del实际删除的是名称,而不是对象
### 字典遍历
for … in dict
遍历item,即kv对
In [84]: for item in d.items():
…: print(item)
…:
(‘a’, 1)
(‘b’, [])
In [85]: for k,v in d.items():
…: print(k,v)
…:
a 1
b []
遍历value
for k in d:
print(d[k])
for k in d.keys():
print(d.get(k))
遍历key
In [1]: d = {‘a’:1,’b’:2,’c’:3}
In [2]: for v in d.keys():
…: print(v)
…:
a
b
c
In [6]: for i in d:
…: print(i)
…:
…:
a
b
c
解构:
In [7]: for k,_ in d.items():
…: print(k)
…:
a
b
c
In [8]: for _,v in d.items():
…: print(v)
…:
1
2
3
也有for k,[_,v] in d.items()等多种变化用法
总结:
Python3中,keys、values、items方法返回一个类似一个生成器的可迭代对象,不会把函数的返回结果复制到内存中
Python2中,上面的方法会返回一个新的列表,占据新的内存空间。所以Python2建议使用iterkey、itervalues、iteritems版本,返回一个迭代器,而不是一个copy
### 字典的key
key的要求和set的元素要求一致
hashable可哈希才可以作为key
In [1]: d = {1:0,2.0:3,”abc”:None,(‘Hello’,’world’,’python’):”string”,b’abc’:’135′}
In [2]: d
Out[2]:
{(‘Hello’, ‘world’, ‘python’): ‘string’,
1: 0,
2.0: 3,
‘abc’: None,
b’abc’: ‘135’}
### defaultdict
collections.defaultdict([default_factory[,…]])
第一个参数是default_factory,缺省值是None,它提供一个初始化函数。当key不存在的时候,会调用这个工厂函数来生成key对应的value
In [1]: from collections import defaultdict
In [2]: d1 = {}
In [3]: d2 = defaultdict(list)
In [4]: for k in “abcde”:
…: for v in range(5):
…: if k not in d1.keys():
…: d1[k] = []
…: d1[k].append(v)
…: print(d1)
…:
{‘a’: [0, 1, 2, 3, 4], ‘b’: [0, 1, 2, 3, 4], ‘e’: [0, 1, 2, 3, 4], ‘d’: [0, 1, 2, 3, 4], ‘c’: [0, 1, 2, 3, 4]}
In [8]: for i in ‘mnopq’:
…: for v in range(3):
…: d2[i].append(v)
…: print(d2)
…:
defaultdict(<class ‘list’>, {‘p’: [0, 1, 2], ‘n’: [0, 1, 2], ‘m’: [0, 1, 2], ‘q’: [0, 1, 2], ‘o’: [0, 1, 2]})
### OrderedDict
collections.OrderedDict([items])
key并不是按照加入的顺序排列,可以使用OrderedDict记录顺序
from collections import OrderedDict
In [9]: from collections import OrderedDict
In [10]: import random
In [11]: d = {‘banana’:3,’apple’:4,’pear’:1,’orange’:2}
In [12]: print(d)
{‘pear’: 1, ‘orange’: 2, ‘apple’: 4, ‘banana’: 3}
In [13]: keys = list(d.keys())
In [14]: random.shuffle(keys)
In [15]: print(keys)
[‘pear’, ‘banana’, ‘apple’, ‘orange’]
In [16]: od = OrderedDict()
In [17]: for key in keys:
…: od[key] = d[key]
…: print(od)
…: print(od.keys())
…:
OrderedDict([(‘pear’, 1), (‘banana’, 3), (‘apple’, 4), (‘orange’, 2)])
odict_keys([‘pear’, ‘banana’, ‘apple’, ‘orange’])
OrderedDict:
1、有序字典可以记录元素插入的顺序,打印的时候也是按照这个顺序输出打印
2、3.6版本的Python的字典就是记录key插入的顺序
## 关于盐和hash的问题,以后可以深入了解一下。
本文来自投稿,不代表Linux运维部落立场,如若转载,请注明出处:http://www.178linux.com/87715