Python Collections

原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/12232548.html

collections模块提供了一些可以替换Python标准内建容器如dict、list、set和tuple等的选择。

Counter类型

它是dict的子类,提供了可哈希对象的计数功能。

假设需要统计某个字符串列表中重复项出现的次数,只要实现如下代码即可

from collections import Counter

counter = Counter()

for lang in ['python', 'java', 'python', 'nodejs', 'python', 'nodejs']:
    counter[lang] += 1

print(counter)

Console Output

Counter({'python': 3, 'nodejs': 2, 'java': 1})

Reference

https://docs.python.org/3/library/collections.html

猜你喜欢

转载自www.cnblogs.com/agilestyle/p/12232548.html