collections模块之其他数据结构

本文介绍了Python标准库collections中的四种常用数据结构:计数器、双端队列、有序字典和带默认值的字典,并提供了详细的代码示例。

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

1. 计数器

可以使用 Counter(seq) 对序列中出现的元素个数进行统计。

例如,我们可以统计一段文本中出现的单词及其出现的次数:

from string import punctuation

sentence = "One, two, three, one, two, tree, I come from China."

words_count = collections.Counter(sentence.translate(punctuation).lower().split())
print(words_count)
Counter({'two': 2, 'one': 2, 'from': 1, 'i': 1, 'tree': 1, 'three': 1, 'china': 1, 'come': 1})

2. 双端队列

双端队列支持从队头队尾出入队:

dq = collections.deque()

for i in range(10):
    dq.append(i)

print(dq)

for i in range(10):
    print(dq.pop(), end=' ')

print(dq)

for i in range(10):
    dq.appendleft(i)

print(dq)

for i in range(10):
    print(dq.popleft(), end=' ')
deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
9 8 7 6 5 4 3 2 1 0
deque([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
9 8 7 6 5 4 3 2 1 0

与列表相比,双端队列在队头的操作更快:

lst = []
dq = collections.deque()

%timeit -n100 lst.insert(0, 10)
%timeit -n100 dq.appendleft(10)
100 loops, best of 3: 598 ns per loop
100 loops, best of 3: 291 ns per loop

3. 有序字典

items = (
    ('A', 1),
    ('B', 2),
    ('C', 3)
)

regular_dict = dict(items)
ordered_dict = collections.OrderedDict(items)

print('Regular Dict:')
for k, v in regular_dict.items():
    print(k, v)

print('Ordered Dict:')
for k, v in ordered_dict.items():
    print(k, v)
Regular Dict:
A 1
C 3
B 2
Ordered Dict:
A 1
B 2
C 3

4. 带默认值的字典

对于 Python 自带的词典 d,当 key 不存在的时候,调用 d[key] 会报错,但是 defaultdict 可以为这样的 key 提供一个指定的默认值,我们只需要在定义时提供默认值的类型即可,如果 key 不存在返回指定类型的默认值:

dd = collections.defaultdict(list)

print(dd["foo"])

dd = collections.defaultdict(int)

print(dd["foo"])

dd = collections.defaultdict(float)

print(dd["foo"])
[]
0
0.0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值