【问题标题】:Python Most Common values in a List [closed]列表中的Python最常见值[关闭]
【发布时间】:2018-06-07 07:52:25
【问题描述】:

我需要一个从列表中返回最常见值的函数。如果有多个最常见的值,则返回所有值。

l = [1, 1, 2, 2, 4]

def most_common(l):
    #some code 
    return common

这应该返回:

[1, 2]

因为它们都出现了两次。

我很惊讶没有简单的功能。我已经尝试过收藏,但似乎无法弄清楚这一点。

【问题讨论】:

标签: python list


【解决方案1】:

您可以先将 collections.defaultdict 中的项目分组,并将计数作为值:

from collections import defaultdict

l = [1, 1, 2, 2, 4]

counts = defaultdict(int)
for number in l:
    counts[number] += 1

print(counts)
# defaultdict(<class 'int'>, {1: 2, 2: 2, 4: 1})

然后你可以从这个字典中找到最常见的值:

most_common = [k for k, v in counts.items() if v == max(counts.values())]

print(most_common)
# [1, 2]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 2015-02-18
    • 1970-01-01
    相关资源
    最近更新 更多