python Counter

from collections import Counter


L1 = 'iuasdhfiuhaefi'
L2 = [1,2,3,4,5,6,6,6,7,7,8,8,8,11,2,1]
L3 = {1:2,3:4,5:6}
L4 = {1,2,23,4,5,6,76,7}
print(Counter(L1))
print(Counter(L2))
print(Counter(L3)-Counter(L3))
print(Counter(L4))
# Counter({'i': 3, 'u': 2, 'a': 2, 'h': 2, 'f': 2, 's': 1, 'd': 1, 'e': 1})
# Counter({6: 3, 8: 3, 1: 2, 2: 2, 7: 2, 3: 1, 4: 1, 5: 1, 11: 1})
# Counter()
# Counter({1: 1, 2: 1, 4: 1, 5: 1, 6: 1, 7: 1, 76: 1, 23: 1})
print('-----1')
c = Counter(a=3,b=1)
d = Counter(a=1,b=2)
print(c+d)
print(c&d)  # 取最小
print(c|d)  # 取最大
# Counter({'a': 4, 'b': 3})
# Counter({'a': 1, 'b': 1})
# Counter({'a': 3, 'b': 2})
print('-----2')
c = Counter(a=3,b=1,c=2)
print(c.values())   # 取值
# print(c.clear())    # 清空
print(c.items())
print('most_common',c.most_common())
print('most_common',c.most_common()[::-1])
# dict_values([3, 1, 2])
# dict_items([('a', 3), ('b', 1), ('c', 2)])
# most_common [('a', 3), ('c', 2), ('b', 1)]
# most_common [('b', 1), ('c', 2), ('a', 3)]
c = Counter(a=3,b=1,c=0)
for k,v in c.items():
    print(k,v)
print(c)
c+=Counter()
print(c)
print(c+Counter(L1))
c.update(Counter(L1))
print(c)
print(c-Counter(L1))

c = Counter()
# a 3
# b 1
# c 0
# Counter({'a': 3, 'b': 1, 'c': 0})
# Counter({'a': 3, 'b': 1})
# Counter({'a': 5, 'i': 3, 'u': 2, 'h': 2, 'f': 2, 'b': 1, 's': 1, 'd': 1, 'e': 1})
# Counter({'a': 5, 'i': 3, 'u': 2, 'h': 2, 'f': 2, 'b': 1, 's': 1, 'd': 1, 'e': 1})
# Counter({'a': 3, 'b': 1})
posted @ 2023-02-03 15:18  recoder_mk  阅读(18)  评论(0编辑  收藏  举报