Python Counter函数
Python Counter函数是Python中collections模块中的一个工具函数,它可以用来统计可迭代对象中元素的出现次数。它是一个无序的容器类型,以字典的键值对形式存储,其中元素作为key,其出现的次数作为value。
使用方法
使用Counter函数需要先导入collections模块:
import collections
就可以使用Counter函数了,它接受一个可迭代对象作为参数,比如一个列表:
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] counter = collections.Counter(list1)
调用Counter函数后,会返回一个Counter类型的对象,可以使用它的属性和方法来操作,比如查看元素出现的次数:
print(counter[1]) # 输出1
也可以使用most_common方法,查看出现次数最多的元素:
print(counter.most_common()) # 输出[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1)]
还可以使用update方法,把另一个可迭代对象中的元素添加到Counter中:
list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] counter.update(list2)
这样,Counter中就会多出10这个元素,而且它的出现次数为2:
print(counter[10]) # 输出2
可以使用elements方法,把Counter中的元素按照出现次数重新组织成一个可迭代对象:
print(list(counter.elements())) # 输出[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]