統計元素數量,並返回字典,鍵為元素,值為個數
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})