Python是Lis中最常见的值

2024-04-19 12:35:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个从列表中返回最常用值的函数。如果有多个最常用的值,则返回所有这些值。你知道吗

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

def most_common(l):
    #some code 
    return common

这将返回:

[1, 2]

因为它们都出现过两次。你知道吗

我很惊讶没有简单的函数。我试过收集,但似乎无法解决这个问题。你知道吗


Tags: 函数most列表returndefcodesomecommon
1条回答
网友
1楼 · 发布于 2024-04-19 12:35:45

您可以首先将^{}中的项分组,并将计数作为值:

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]

相关问题 更多 >