Python中,Counter
是一个字典子类,用于计算可哈希对象(如列表、元组、字符串)中元素的出现次数。Counter
可以用于快速计数元素,而不需要手动循环计算。以下是一些Counter
的用法:
-
导入
Counter
:from collections import Counter -
my_list = [1, 2, 3, 2, 4, 3, 1, 2, 2] my_counter = Counter(my_list)
-
访问
Counter
对象中的元素:print(my_counter[2])
-
获取
Counter
对象中最常见的元素print(my_counter.most_common(2))
输出:
[(2, 4), (1, 2)]
以上代码返回出现次数前两个的元素列表和它们的出现次数。
-
更新
Counter
对象:my_counter.update([1, 2, 2, 3, 3, 3])
以上代码增加了一些元素,并更新它们的出现次数
-
合并两个
Counter
对象:other_list = [1, 2, 2, 4, 5, 5] other_counter = Counter(other_list) my_counter += other_counter
创建一个空字典:
counter = Counter()