1.3 collections.deque
deque(maxlen=N)
新建一個固定大小的隊列,如果新加入元素時隊列已滿,最老的元素會被除掉。
隊列,插入、刪除元素都是O(1)
列表/棧,在開頭插入、刪除元素都是O(N)
1.4 heapq
堆,適用于查找一組元素中topN的元素集合,元素個數較少。
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums))
print(heapq.nsmallest(3, nums))
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
1.6collections.defaultdict
字典,一個key對應多個value
from collections import defaultdict
a = defaultdict(list)
a['a'].append(1)
a['a'].append(1)
a['a'].append(2)
1.7有序列表
`collections.OrderedDict
from collections import OrderedDict
a = OrderedDict()
a[1] = 'adsf'
a['asdf'] = 111
print(a)
原理:內部有一個雙向鏈表
空間是普通字典的兩倍