自学Python--常用模块之collections模块

堆栈:先进后出

队列:先进先出

 

namedtuple:命名元组

一个点的二维坐标可以表示为:p = (1, 2)

from collections import namedtuple


Point = namedtuple('point', ['x', 'y', 'z'])
p = Point(1, 2, 3)
print(p) # point(x=1, y=2, z=3)
print(p.x, p.y, p.z) # 1 2 3

Card = namedtuple('card', ['suits', 'number'])
card1 = Card('红桃', 2)
card2 = Card('黑桃', 9)
print(card1) # card(suits='红桃', number=2)
print(card2) # card(suits='黑桃', number=9)Card = namedtuple('card', ['suits', 'number'])

 

deque:双端队列

list按索引访问速度快,但插入和删除速度慢,因为list是线性存储。deque插入和删除速度快,适用于队列和堆栈

队列:先进先出,如买票

import queue
q = queue.Queue()
q.put(1)
q.put(2)
q.put(3)
q.put(4)
q.put(5)
q.put(6)
print(q.qsize()) # 6
print(q.get()) # 1
print(q.get()) # 2
print(q.get()) # 3
print(q.get()) # 4
print(q.get()) # 5
print(q.get()) # 6
print(q.qsize()) # 0
print(q.get()) # 不输出,等待,不执行下一步

双端队列:可以从头或者尾取值

from collections import deque


q = deque([1, 2]) # [1, 2]
q.append('a') # 从后放数据 [1, 2, 'a']
q.appendleft('b') # 从前放数据 # ['b', 1, 2, 'a']
q.insert(1, 3) # 队列没有插入方法 ['b', 3, 1, 2, 'a']
print(q.pop()) # 从后取数据 'a'
print(q.popleft()) # 从前面取数据 'b'

 

OrderedDict:有序字典

from collections import OrderedDict

od = OrderedDict([('a', 1), ('b', 3), ('c', 3)])
print(od) # OrderedDict([('a', 1), ('b', 3), ('c', 3)])
print(od['a']) # 1
for i in od:
    print(i) # a,b,c

 

你可能感兴趣的:(自学Python)