Python collections.Counter()

Counter实现了计数操作,可用于统计迭代器中元素个数

from collenctions import Counter
nums = [1,1,2,2,1,3,4]
cnt = Counter(nums)
print(cnt)
# Counter({1: 3, 2: 2, 3: 1, 4: 1})

Counter中不存在的元素默认为0,不用声明即可进行算术操作

cnt[5] += 1
print(cnt)
# Counter({1: 3, 2: 2, 3: 1, 4: 1, 5: 1})

删除Counter中的元素可以使用pop()或del

cnt.pop(2)
del cnt[3]
# Counter({1: 3, 4: 1, 5: 1})

通过转化成list获取所有元素

print(list(cnt.elements()))
# [1, 1, 1, 4, 5]

most_common(k)方法获取最多的k个元素

print(cnt.comment(2))
# [(1, 3), (4, 1)]

你可能感兴趣的:(python学习积累,python)