在列表中找到出现次数最多的项

79

在Python中,我有一个列表:

L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]  

我想找出发生最多次的项目。我知道如何解决它,但我需要最快的方法。我知道有一种很好的Pythonic答案。

14个回答

1

我想提供另一个看起来不错且适用于列表的快速解决方案。

def mc(seq=L):
    "max/count"
    max_element = max(seq, key=seq.count)
    return (max_element, seq.count(max_element))

您可以使用Ned Deily提供的代码进行基准测试,该测试结果适用于最小的测试用例:

3.5.2 (default, Nov  7 2016, 11:31:36) 
[GCC 6.2.1 20160830] 

dict iteritems (4, 6) 0.2069783889998289
dict items (4, 6) 0.20462976200065896
defaultdict iteritems (4, 6) 0.2095775119996688
sort groupby generator expression (4, 6) 0.4473949929997616
sort groupby list comprehension (4, 6) 0.4367636879997008
counter (4, 6) 0.3618192010007988
max/count (4, 6) 0.20328268999946886

但要注意,它效率低下,因此对于大型列表会变得非常缓慢!


1
如果您在解决方案中使用numpy进行更快的计算,请使用以下内容:
import numpy as np
x = np.array([2,5,77,77,77,77,77,77,77,9,0,3,3,3,3,3])
y = np.bincount(x,minlength = max(x))
y = np.argmax(y)   
print(y)  #outputs 77

0
以下是我想出的解决方案,如果字符串中有多个字符都具有最高频率。
mystr = input("enter string: ")
#define dictionary to store characters and their frequencies
mydict = {}
#get the unique characters
unique_chars = sorted(set(mystr),key = mystr.index)
#store the characters and their respective frequencies in the dictionary
for c in unique_chars:
    ctr = 0
    for d in mystr:
        if d != " " and d == c:
            ctr = ctr + 1
    mydict[c] = ctr
print(mydict)
#store the maximum frequency
max_freq = max(mydict.values())
print("the highest frequency of occurence: ",max_freq)
#print all characters with highest frequency
print("the characters are:")
for k,v in mydict.items():
    if v == max_freq:
        print(k)

输入:"hello people"

输出:

{'o': 2, 'p': 2, 'h': 1, ' ': 0, 'e': 3, 'l': 3}

最高出现频率:3

字符为:

e

l

-3
可能是这样的: < p >测试列表 = [1, 2, 3, 4, 2, 2, 1, 4, 4] print(max(set(testList), key = testList.count))< /p >

一个Set数据结构将会移除重复项,使得你的计数变得无关紧要。 - aidanmelen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接