python常用collections lib介绍

本文详细介绍了Python3标准库中的collections模块,包括Counter用于计数、defaultdict提供默认值、deque实现双向队列、OrderedDict保持插入顺序、namedtuple允许通过属性名访问tuple元素以及ChainMap合并多个字典。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介
本文主要介绍python3下collections lib。主要lib如下: - Counter - defaultdict - deque - OrderedDict - namedtuple - ChainMap
Counter
计算出现次数
>>> import collections
>>> collections.Counter([1,1,2,3,4,4,4,5])
Counter({4: 3, 1: 2, 2: 1, 3: 1, 5: 1})
>>> collections.Counter("huuinn")
Counter({'n': 2, 'u': 2, 'h': 1, 'i': 1})
defaultdict
当对应的键值不存在时,返回默认值,而不是报错
>>> import collections
>>> d = collections.defaultdict(int)
>>> d[0]
0
>>> d[2]
0

>>> d = collections.defaultdict(lambda:100)  # 想默认值非0时返回100时
>>> d[1]
100
>>> d[11]
100

>>> d = dict()
>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 0

deque
可双向操作的队列
>>> import collections
>>> d = collections.deque([1,2,3,4])
>>> d.pop()
4
>>> d.popleft()
1
>>> d
deque([2, 3])
>>> d.appendleft(4)
>>> d.append(1)
>>> d
deque([4, 2, 3, 1])
OrderedDict
值按顺序添加到对象里
>>> import collections
>>> o = collections.OrderedDict()
>>> o['first']=1
>>> o['second']=2
>>> o
OrderedDict([('first', 1), ('second', 2)])

>>> o['second']=3
>>> o
OrderedDict([('first', 1), ('second', 3)])
namedtuple
让tuple类型的元素当作类成员属性来访问
>>> import collections
>>> N = collections.namedtuple('Fruit',['apple','grape'])
>>> N(*[1,2])
Fruit(apple=1, grape=2)
>>> n = N(*[1,2])
>>> n
Fruit(apple=1, grape=2)
>>> n.apple
1
>>> n.grape
2
ChainMap
多个字典合并
>>> import collections
>>> c = collections.ChainMap({1:2,3:4},{5:6,7:8})
>>> c = c.new_child({9:10,11:12})
>>> c
ChainMap({9: 10, 11: 12}, {1: 2, 3: 4}, {5: 6, 7: 8})
>>> c[9]
10
>>> c.maps
[{9: 10, 11: 12}, {1: 2, 3: 4}, {5: 6, 7: 8}]
>>> c.maps[0]
{9: 10, 11: 12}


查看原文:https://www.huuinn.com/archives/500
更多技术干货:风匀坊
关注公众号:风匀坊
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值