参考 Find
most frequent element in a list in Python (tutorialspoint.com)
1. 法一:with max and count
1 2 3 4 5 6
| # Given list listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
res = max(set(listA), key = listA.count) print("Element with highest frequency:\n",res) # 输出 45
|
2. 法二:with Counter
1 2 3 4 5 6 7 8 9
| from collections import Counter
# Given list listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
occurence_count = Counter(listA) res=occurence_count.most_common(1)[0][0] print("Element with highest frequency:\n",res) # 输出 45
|
3. 法三:with mode
返回众数
1 2 3 4 5 6 7
| from statistics import mode # Given list listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
res=mode(listA) print("Element with highest frequency:\n",res) # 输出 45
|
补充:关于 Counter
将一个 list 传入 Counter,将返回一个包含每个元素出现次数的字典
1 2 3 4 5 6 7 8 9 10
| from collections import Counter
# Given list listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
occurence_count = Counter(listA) occurence_count.keys() # dict_keys([45, 20, 11, 50, 17, 13]) occurence_count.values() dict_values([3, 1, 1, 2, 1, 1])
|
most_common([n])
方法:
返回前n个出现次数最多的元素及其数量。
如果省略n或None,将返回计数器中的所有元素。
具有相同计数的元素可以任意排序
1 2 3 4 5
| occurence_count.most_common(1) # [(45, 3)]
occurence_count.most_common(2) #[(45, 3), (50, 2)]
|