一个 Counter 是一个 dict 的子类,用于计数可哈希对象.
统计元素出现次数:Counter
from collections import Counternew_list = ['a', 'a', 'a', 'b', 'b', 'b', 'c']print(Counter(new_list)) # 返回一个Counter对象"""Counter({'a': 3, 'b': 3, 'c': 1})"""
展开每个计数值大于等于1的元素:elements()
new_counter = Counter(new_list)print(new_counter.elements()) # 返回一个迭代器"""<itertools.chain object at 0x7ffde8262050>"""print(list(new_counter.elements()))"""['a', 'a', 'a', 'b', 'b', 'b', 'c']"""
统计元素出现最多的元素:Counter.most_common()
返回一个列表,其中包含 n 个最常见的元素及出现次数,按常见程度由高到低排序
from collections import Counterlist_info = 'hello worldeeeee'list1 = [1, 3, 3, 4, 1, 4]print(Counter(list_info))print(Counter(list_info).most_common()[0][0])print(max(set(list_info), key=list_info.count))-------------------------#Counter({'e': 6, 'l': 3, 'o': 2, 'h': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})#e#e
