【问题标题】:Pythonic way to find all elements with the highest frequency? [duplicate]Pythonic方法来查找频率最高的所有元素? [复制]
【发布时间】:2017-07-08 10:04:56
【问题描述】:

我有一个这样的列表:

lst = [1, 3, 5, 1, 5, 6, 1, 1, 3, 4, 5, 2, 3, 4, 5, 3, 4]

我想找出所有最常出现的元素。 所以我想:

most = [1, 3, 5]

1、3、5 出现次数最多,为 4 次。什么是一种快速的、pythonic 的方式来做到这一点?我尝试了这里显示的方法:

How to find most common elements of a list?

但它只给了我前 3 名,我需要所有元素。谢谢。

【问题讨论】:

  • 链接中的那个答案做了一个切片popular_words[:3],只返回前3个。实际的计数器包含所有总数,而不仅仅是前3个。

标签: python list max frequency


【解决方案1】:

使用collections.Counter 和一个列表理解

from collections import Counter

lst = [1, 3, 5, 1, 5, 6, 1, 1, 3, 4, 5, 2, 3, 4, 5, 3, 4]
r = [x for x, _ in Counter(lst).most_common(3)]
print(r)
# [1, 3, 5]

您可以通过在计数器值上使用max 来概括计数最高的值:

c = Counter(lst)
m = max(c.values())
r = [k for k in c if c[k] == m]
print(r)
# [1, 3, 5]

对于大型可迭代对象,为了有效地遍历计数器并在获取所需项目后停止,您可以使用 itertools.takewhilemost_common,不带任何参数:

from itertools import takewhile

c = Counter(lst)
m = max(c.values())
r = [x for x, _ in takewhile(lambda x: x[1]==m, c.most_common())] 
print(r)
# [1, 3, 5]

您不必遍历 counter 对象中的所有项目,尽管使用most_common 对项目进行排序会有一些开销;所以我确定这是否绝对毕竟有效。你可以用timeit做一些实验。

【讨论】:

  • 这是可行的,但我想找出出现频率最高的 所有 元素,而不仅仅是前 3 个。不过,谢谢。
  • @ArjunVasudevan 我已经针对一般情况进行了更新
【解决方案2】:

如果您想打印所有最频繁的,您可以执行以下操作,

    from collections import Counter
    words=[1, 3, 5, 1, 5, 6, 1, 1, 3, 4, 5, 2, 3, 4, 5, 3, 4]
    most= [word for word, word_count in Counter(words).most_common()]
    print (most)
>>> 
[1, 3, 5, 4, 2, 6]

请注意,如果你想限制,你可以在most_common()函数里面输入数字。例如:...most_common(3)]。希望这能回答你的问题。

【讨论】:

    【解决方案3】:

    你也可以通过itertools模块和list comprehension中的groupby得到同样的结果:

    from itertools import groupby
    
    a = [1, 3, 5, 1, 5, 6, 1, 1, 3, 4, 5, 2, 3, 4, 5, 3, 4]
    most_common = 3
    final = [k for k,v in groupby(sorted(a), lambda x: x) if len(list(v)) > most_common]
    

    输出:

    print(final)
    >>> [1, 3, 5]
    

    【讨论】:

    • 好吧,这假设你已经有一个先验阈值
    • 是的。这是真的。但是它可以扩展到处理所有情况。
    猜你喜欢
    • 2021-12-11
    • 2013-03-21
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 2019-08-15
    • 1970-01-01
    • 2011-10-10
    相关资源
    最近更新 更多