0. 字典初始化
d = {‘a’:1,’b’:2}
或 d={}
d[‘a’] = 1
d[‘b’] = 2
是不是和json格式数据很相似,语法和JavaScript又很相似
1. 变量接受序列分解:
p = (3.14,8.23)
X,Y = p
print(x,y)
3.14,8.23
2. Collections.deque 固定长度队列。
>>> from collections import deque
>>> p = deque(maxlen = 2)
>>> p.append(3.14)
>>> p.append(8.23)
>>> p
deque([3.14, 8.23], maxlen=2)
3. heapq 最大值最小值。
>>> import heapq
>>> p = [3.14,8.23,7.10]
>>> heapq.nlargest(1,p)
[8.23]
>>> heapq.nsmallest(1,p)
[3.14]
5.找出两个字典相同键 和相同项
>>> from collections import OrderedDict
>>> d = {}
>>> d['a'] = 1
>>> d['c'] = 3
>>> d['b'] = 2
>>> dd = {}
>>> dd['a'] = 3
>>> dd['e'] = 5
>>> dd['b'] = 2
>>> d.keys() & dd.keys()
{'a', 'b'}
>>> d.items() & dd.items()
{('b', 2)}
6 去除数组或字典值重复的元素 set
>>> d ={1,1,2,2,3,3,4,5}
>>> set(d)
{1, 2, 3, 4, 5}
7 截取数组元素
>>> d = [1,1,2,2,3,3,4,5]
>>> d[2:4]
[2, 2]
>>> d[2:5]
[2, 2, 3]
8 统计元素出现次数Counter.most_common。
>>> d = [1,1,1,2,2,4,5]
>>> from collections import Counter
>>> master = Counter(d).most_common(2)
>>> print(master)
[(1, 3), (2, 2)]
4. collections.OrderedDict 有序字典
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d['a'] = 1
>>> d['c'] = 3
>>> d['b'] = 2
>>> print(d)
OrderedDict([('a', 1), ('c', 3), ('b', 2)])
9.数组排序 operator.itemgetter
>>> from operator import itemgetter
>>> d = [2,1,5,4,3]
>>> sorted(d)
[1, 2, 3, 4, 5]
10.字典排序 sort
>>> from operator import itemgetter
>>> p = [{'x':'3','y':'3'},{'x':'4','y':'4'},{'x':'2','y':'2'},{'x':'1','y':'1'}]
>>> p.sort(key=itemgetter('x'))
>>> print(p)
[{'x': '1', 'y': '1'}, {'x': '2', 'y': '2'}, {'x': '3', 'y': '3'}, {'x': '4', 'y': '4'}]
11. lambda 表达式
>>> p = [{'x':'3','y':'3'},{'x':'4','y':'4'},{'x':'2','y':'2'},{'x':'1','y':'1'}]
>>> pLamb = [n['x'] > '2' for n in p]
>>> print(pLamb)
[True, True, False, False]
12 compress 与 11项 结合使用。
>>> from itertools import compress
>>> list(compress(p,pLamb))
[{'x': '3', 'y': '3'}, {'x': '4', 'y': '4'}]
13.逻辑上合并对象
>>> p = {'x':1,'y':2}
>>> p2 = {'y':3,'z':4}
>>> from collections import ChainMap
>>> c = ChainMap(p,p2)
>>> print(c)
ChainMap({'x': 1, 'y': 2}, {'y': 3, 'z': 4})
>>> list(c.keys())
['x', 'z', 'y']