如果要查找列表中每个元素的出现位置,可以使用集合中的Counter模块: –
>>> 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()以指定您想要的最常见元素数量: –
>>> count.most_common(2)
[('a', 2), ('c', 2)]
更新: –
您还可以先查找最大计数,然后找到具有该值的元素总数,然后您可以将其用作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']