1. 程式人生 > >Python >List工具包

Python >List工具包

array

陣列
from array import array
a = array(‘H’,[4000, 10, 700, 22222])
sum(a)

deque

佇列
from collections import deque
d = deque([“task1”, “task2”, “task3”])
d.append(“task4”)
print(“Handling”, d.popleft())

bisect

中分排序:自動將加入的資料進行中分排序
import bisect
scores = [(100, ‘perl’), (200, ‘tcl’), (400, ‘lua’), (500, ‘python’)]
bisect.insort(scores, (300, ‘ruby’))

heapq

堆:heapq模組提供的功能實現堆基於常規列表,將訪問最多的元素放在最前
from heapq import heapify ,heappop,heappush
data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapify(data) # rearrange the list into heap order
heappush(data, -5) # add a new entry
[heappop(data) for i in range(3)] # fetch the three smallest entries