Python内建模块collections是一些有用的集合类容器,它们提供了更快、更方便的方法来处理一些常见的数据处理任务。在这里,我们将学习如何使用collections模块。
collections模块中的常用类
在collections模块中有几个常见的类,包括:
- Counter:用于计数,返回一个字典。
- defaultdict:当字典中的key不存在时提供一个默认值。
- OrderedDict:有序字典,可以按照键的顺序进行遍历。
- deque:双向队列,可以从两端进行插入和删除操作。
# Counter类示例:
from collections import Counter
c = Counter(['apple', 'banana', 'apple', 'cherry', 'apple', 'banana'])
print(c)
# 输出:Counter({'apple': 3, 'banana': 2, 'cherry': 1})
print(c.most_common()) # 输出:[('apple', 3), ('banana', 2), ('cherry', 1)]
# defaultdict类示例:
from collections import defaultdict
d = defaultdict(int) # 设置默认值为0
d['apple'] += 2
d['banana'] += 3
print(d) # 输出:defaultdict(<class 'int'>, {'apple': 2, 'banana': 3, 'cherry': 0})
实用示例
示例1:统计句子中每个单词出现的次数
from collections import Counter
sentence = "This is a test sentence for counting the words"
word_counts = Counter(sentence.split()) # 将句子拆分成单词并统计出现次数
for word, count in word_counts.items():
print(f"{word}: {count}")
输出结果:
This: 1
is: 1
a: 1
test: 1
sentence: 1
for: 1
counting: 1
the: 1
words: 1
示例2:使用deque实现斐波那契数列
from collections import deque
def fibonacci_sequence(n):
seq = deque([0, 1], maxlen=2) # 初始化deque,设置最大长度为2
if n == 0:
return []
elif n == 1:
return [0]
elif n == 2:
return list(seq)
else:
for i in range(2, n):
seq.append(seq[0] + seq[1]) # 添加下一个斐波那契数
return list(seq)
print(fibonacci_sequence(10)) # 输出:[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
以上就是关于collections模块的使用攻略,希望对你有帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python中内建模块collections如何使用 - Python技术站