Python collections and heapq
1. queue
1.1 collections.deque
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import collections
queue = collections.deque()
queue.append(5) queue.appendleft(10)
queue.append(6) queue.append(7)
print(queue)
cur = queue.popleft() cur = queue.pop()
print(queue)
|
1.2 queue.Queue()
1 2 3 4 5 6 7 8 9
| from queue import Queue q = Queue() q.put(5) q.put(3) q.put(9)
print(q.qsize()) print(q.get()) print(q.qsize())
|
1.3 queue.PriorityQueue()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| from queue import PriorityQueue
pq = PriorityQueue()
pq.put((1, 2)) pq.put((1, 0)) pq.put((5, 0)) pq.put((2, 3))
while not pq.empty(): print (pq.get())
|
存放自定义类型:
自定义数据类型,需要自定义 __cmp__
或者 __lt__
比价函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| from queue import PriorityQueue
class Job(object): def __init__(self, priority, description): self.priority = priority self.description = description
def __lt__(self, other): return self.priority < other.priority
q2 = PriorityQueue() q2.put(Job(5, 'Mid-level job')) q2.put(Job(10, 'Low-level job')) q2.put(Job(1, 'Important job'))
print(q2.qsize())
while not q2.empty(): next_job = q2.get() print(next_job.description)
|
2. heapq
1 2 3 4 5 6 7 8 9 10
| from heapq import nsmallest, nlargest
lst = [5, 8, 0, 4, 6, 7]
print(nsmallest(3, lst))
print(nlargest(3, lst))
|
3. stack is list
1 2 3 4 5 6 7
| a = [1, 5, 22, 2, 7]
a.pop(2)
a.insert(2, 220)
print(a)
|
4. 进制转换 bin, oct, hex, int(‘0b10000’, 2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
dec = int(input("输入数字:")) print("十进制数为:", dec) print("转换为二进制为:", bin(dec)) print("转换为八进制为:", oct(dec)) print("转换为十六进制为:", hex(dec))
int(hex(2*a),16)
|
十进制 与 二进制 的互相转换
1 2 3 4 5 6 7
| In [1]: a = 16
In [9]: bin(a) Out[9]: '0b10000'
In [10]: int('0b10000', 2) Out[10]: 16
|
Reference
Checking if Disqus is accessible...