python collections模块

1.namedtuple

作用:生成可以使用名字来访问元素内容的tuple

# x,y坐标系,表示圆
from collections import namedtuple
Circle = namedtuple('circle', ['x', 'y', 'r'])
c = Circle(2, 10, 3)
print(c)    # circle(x=2, y=10, r=3)
print(c.x)  # 2
print(c.y)  # 10
print(c.r)  # 3
# 扑克牌
from collections import namedtuple
Card = namedtuple('card', ['card_name', 'card_size'])
card = Card('黑桃', 'A')
card1 = Card('红心', '2')
print(card)     # card(card_name='黑桃', card_size='A')
print(card.card_name)       # 黑桃
print(card.card_size)       # A
print(card1.card_size)      # 2

2.dequ

双端队列,可以快速的从另外一侧追加和推出对象

from collections import deque
li = list(range(5))
li = deque(li)
print(li)
li.appendleft('a')
li.append('z')
print(li)
a = li.popleft()
b = li.pop()
print(a, b)
li.insert(0, 'uu')
print(li)
"""
结果:
deque([0, 1, 2, 3, 4])
deque(['a', 0, 1, 2, 3, 4, 'z'])
a z
deque(['uu', 0, 1, 2, 3, 4])
"""

3.OrderedDict

有序字典

from  collections import OrderedDict
dic = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
dic = OrderedDict(dic)
print(dic)  # OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])

4.defaultdict

带有默认值的字典

from collections import defaultdict
li = [11, 22, 33, 44, 55, 77, 88, 99]
dic = {}
dic = defaultdict(list)     # 默认值为list
for i in li:
    if i > 66:
        dic['k1'].append(i)
    else:
        dic['k2'].append(i)


print(dic['k1'])    # [77, 88, 99]
print(dic['k2'])    # [11, 22, 33, 44, 55]

 

posted @ 2019-05-19 22:00  市丸银  阅读(160)  评论(0编辑  收藏  举报