42-python-collections模块

# collections ---  可以给元组命名
from collections import namedtuple
Point = namedtuple('point',['x','y','z'])
p1 = Point(12,3,4)
p2 = Point(4,6,7)
print(p1.x)         # 打印结果 : 12
print(p2.x)         # 打印结果 : 4
print(p1,p2)        # 打印结果 : point(x=12, y=3, z=4) point(x=4, y=6, z=7)

# 队列    FIFO
import queue

q = queue.Queue()
q.put(10)
q.put(2)
q.put(3)
print(q.get())  # 10
print(q.get())  # 2
print(q.get())  # 3
#print(q.get())  # 当没有的时候会停在这 (阻塞)

 

# 双端队列
from collections import deque
dq = deque([1,2])
dq.append('a')      # 从后面放数据
dq.appendleft(4)    # 从前面放数据
dq.insert(2,0)      # [4, 1, 0, 2, 'a']
print(dq.pop())     # 从后面取数据    # 打印结果:a
print(dq.popleft()) # 从前面取数据    # 打印结果:4

 

# 有序字典
from collections import OrderedDict
od = OrderedDict([('a',1),('b',2),('c',3)])
print(od)       # 打印结果:OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(od['a'])  # 打印结果:1
print(od['b'])  # 打印结果:2
print(od['c'])  # 打印结果:3

 

# defaultdict   给 key 添加一个默认的数据
from collections import defaultdict
d = defaultdict(list)
d1 = defaultdict(lambda : 5)
print(d['k'])   # 打印结果:[]
print(d1['k'])   # 打印结果:5

  





posted @ 2018-10-28 21:06  _Q  阅读(92)  评论(0)    收藏  举报