python - Counter简单使用

统计元素数量,并返回字典,键为元素,值为个数

from collections import Counter
lst = ['a','b','c','d','a','b','a','c','c','c']
dic = Counter(lst)
print(dic)
# Counter({'c': 4, 'a': 3, 'b': 2, 'd': 1})

s = 'abcdflxjn,dflsdk,fsd;'
dic = Counter(s)
print(dic)
# Counter({'d': 4, 'f': 3, 'l': 2, ',': 2, 's': 2, 'a': 1, 'b': 1, 'c': 1, 'x': 1, 'j': 1, 'n': 1, 'k': 1, ';': 1})

lst = ['a','b','c','d','a','b','a','c','c','c']
print(Counter(lst).most_common(3))
# 返回n个最大数目的元素
# [('c', 4), ('a', 3), ('b', 2)]

lst1 = ['a','b','c','d','a','b','a','c','c','c']
lst2 = ['b','c','d','a','b','a','c']
a = Counter(lst1)  # Counter({'c': 4, 'a': 3, 'b': 2, 'd': 1})
b = Counter(lst2)  # Counter({'b': 2, 'c': 2, 'a': 2, 'd': 1})
# 相同元素相减
a - b  # Counter({'c': 2, 'a': 1, 'b': 0, 'd': 0})
# 相同键值相加
a + b  # Counter({'a': 3, 'b': 2, 'c': 4, 'd': 1})
# intersection: min(a[x], b[x])
a & b  # Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1})
# union: max(a[x], b[x])
a | b  # Counter({'a': 3, 'b': 2, 'c': 4, 'd': 1})
posted @ 2024-05-04 12:32  wstong  阅读(13)  评论(0编辑  收藏  举报