如果要查找列表中每个元素的出现,可以使用Counter
module from :-collections
>>> x = ['a','a','b','c','c','d']
>>> from collections import Counter
>>> count = Counter(x)
>>> count
Counter({'a': 2, 'c': 2, 'b': 1, 'd': 1})
>>> count.most_common()
[('a', 2), ('c', 2), ('b', 1), ('d', 1)]
因此,前两个元素在您的列表中最为常见。
>>> count.most_common()[0]
('a', 2)
>>> count.most_common()[1]
('c', 2)
或者,您还可以将参数传递给以most_common()
指定所需的most-common
元素数量:-
>>> count.most_common(2)
[('a', 2), ('c', 2)]
更新 : -
您也可以max
先找出计数,然后找到具有该值的元素总数,然后您可以将其用作参数most_common()
: -
>>> freq_list = count.values()
>>> freq_list
[2, 2, 1, 1]
>>> max_cnt = max(freq_list)
>>> total = freq_list.count(max_cnt)
>>> most_common = count.most_common(total)
[('a', 2), ('c', 2)]
>>> [elem[0] for elem in most_common]
['a', 'c']