一 heapq模塊
該模塊提供了堆排序算法的實現
1 創建堆和排序
(1) heapq.heappush()
(2) heap.heapify(list)
2 排序
(1) [heapq.heappop(heap) for _ in range(len(nums))]
(2) num1 = sorted(num1); num2 = sorted(num2)
res = heapq.merge(num1, num2)
3 返回最小值
heapq.heappop(nums)
4 刪除堆中最小元素並加入一個元素
heapq.heaprepalce()
5 獲取堆最大或最小值
(1) heapq.nlargest(3, nums)
(2) heapq.nsmallest(3, nums)
這兩個函數還接受一個key參數,用於dict或其他數據結構類型使用
(3) cheap = heapq.nsmallest(3, portfolio, key=lambda s: s[‘price’])
(4) expensive = heapq.nlargest(3, portfolio, key=lambda s: s[‘price’])
二 itertools模塊
"""
迭代工具模塊
"""
import itertools
# 產生ABCD的全排列
itertools.permutations('ABCD')
# 產生ABCDE的五選三組合
itertools.combinations('ABCDE', 3)
# 產生ABCD和123的笛卡爾積
itertools.product('ABCD', '123')
# 產生ABC的無限循環序列
itertools.cycle(('A', 'B', 'C'))
e:
temp3 = itertools.product('ABCD', '123')
for i in temp3:
print(i)
>>>
('A', '1')
('A', '2')
('A', '3')
('B', '1')
('B', '2')
('B', '3')
('C', '1')
('C', '2')
('C', '3')
('D', '1')
('D', '2')
('D', '3')
三 collections模塊
from collections import Counter
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around',
'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes',
'look', 'into', 'my', 'eyes', "you're", 'under'
]
counter = Counter(words)
print(counter.most_common(3))
>>>
[('eyes', 8), ('the', 5), ('look', 4)]