collections模块之Counter()
Counter: 便捷快速计数(支持所有存储结构),将元素计数,并返回一个字典,key为元素,value为该元素的数量,与count不同,count() 只会记录输入元素的数量
演示:
# 具体演示·以串为例(没办法,串最好打,直接引号里面输字符)
from collections import Counter
test_str="cabbba"
res_dic=Counter(test_str)
# 结果按数量降序存储,就是先存多的元素
print(res_dic)
# 按被处理串中元素顺序
print(dict(res_dic))
# 由于Counter 结果是字典,故字典的操作都可进行
print(res_dic.items()) # dict.items() 取字典的key与value
print(res_dic.keys)
print(res_dic.values())
# 按数量降序排列
print(sorted(res_dic.items(),key=lambda x:-x[-1]))
# 按元素查数量,按数量查元素 通过遍历方法
for k,v in res_dic.items():if v==2:print(k)# if k=="元素":# print(i)
结果:
结果按数量降序存储,就是先存多的元素
Counter({'b': 3, 'a': 2, 'c': 1})
按被处理串中元素顺序
{'c': 1, 'a': 2, 'b': 3}
由于Counter 结果是字典,故字典的操作都可进行
dict_items([('c', 1), ('a', 2), ('b', 3)])
<built-in method keys of Counter object at 0x00000281F2BBE7F0>
dict_values([1, 2, 3])
按数量降序排列
[('b', 3), ('a', 2), ('c', 1)]
按元素查数量,按数量查元素 通过遍历方法
a
Counter.most_common()
返回一个列表,包含counter中n个最大数目的元素(就是按数量降序输出n个元素),
如果忽略n或者为None,most_common()将会返回counter中的所有元素,
元素有着相同数目的将会选择出现早的元素
演示:
test_str1="aaassffhhghhhhwewwwjggh"
print("返回2个数量最多的元素")
print(Counter(test_str1).most_common(2))
# 存在相同数目元素时,且在most_common范围内
print("存在相同数目元素时,且在most_common范围内")
test_str2="aabbcccccddd"
print(Counter(test_str2).most_common(3))
# 调换 ab位置
test_str3="bbaacccccddd"
print("调换相同数量元素位置")
print(Counter(test_str3).most_common(3))
结果:
返回2个数量最多的元素
[('h', 7), ('w', 4)]
存在相同数目元素时,且在most_common范围内
[('c', 5), ('d', 3), ('a', 2)]
调换相同数量元素位置
[('c', 5), ('d', 3), ('b', 2)]
update()
将俩个可迭代对象(可迭代对象是一个元素序列,而非(key,value)对构成的序列)
中所有元素相加,是数目相加而非替换它们
dic1 = {'a': 3, 'b': 4, 'c': 0, 'd': -2, "e": 0}
dic2 = {'a': 3, 'b': 4, 'c': 0, 'd': 2, "e": -1, "f": 6}
a = Counter(dic1)
print(a)
# 结果:Counter({'b': 4, 'a': 3, 'c': 0, 'e': 0, 'd': -2})
b = Counter(dic2)
print(b)
# 结果:Counter({'f': 6, 'b': 4, 'a': 3, 'd': 2, 'c': 0, 'e': -1})
a.update(b)
print(a)
# 结果:Counter({'b': 8, 'a': 6, 'f': 6, 'c': 0, 'd': 0, 'e': -1})
subtract()
俩个可迭代对象元素相减,是数目相减而不是替换它们
dic1 = {'a': 3, 'b': 4, 'c': 0, 'd': -2, "e": 0}
dic2 = {'a': 3, 'b': 4, 'c': 0, 'd': 2, "e": -1, "f": 6}
a = Counter(dic1)
print(a)
# 结果:Counter({'b': 4, 'a': 3, 'c': 0, 'e': 0, 'd': -2})
b = Counter(dic2)
print(b)
# 结果:Counter({'f': 6, 'b': 4, 'a': 3, 'd': 2, 'c': 0, 'e': -1})
a.subtract(b)
print(a)
# 结果:Counter({'e': 1, 'a': 0, 'b': 0, 'c': 0, 'd': -4, 'f': -6})