首页 > 编程语言 > 详细

python collections模块

时间:2019-05-19 22:39:01      阅读:137      评论:0      收藏:0      [点我收藏+]

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]

 

python collections模块

原文:https://www.cnblogs.com/wt7018/p/10891074.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!