如何在不使用Counter()的情况下找到列表中最常见的元素?

-1 投票
2 回答
958 浏览
提问于 2025-04-18 02:19

不使用 Counter() 类,而是用普通的字典,我该如何找到列表中出现最频繁的元素呢?

给定的列表是:

my_list = ['duck', 'duck', 'horse', 'goose', 'bird', 'goose']

我希望输出的结果类似于这样:

most_common: duck, goose

如果有多个元素出现的次数相同,并且都是最多的,它们都会显示出来,并且可以以字符串的形式输出,而不是各自单独成列表。

2 个回答

0

首先,使用预定义的类名来命名对象是个坏习惯。你在问题中用了 list 这个名字。

>>> lst = ['duck','duck','horse','goose','bird','goose']
>>> temp=set(lst)
>>> result={}
>>> for i in temp:
     result[i]=lst.count(i)


>>> result
{'goose': 2, 'horse': 1, 'bird': 1, 'duck': 2}
>>> 
2
print([item for item in count_dict if count_dict[item] == maxi])
# ['goose', 'duck']

使用普通的字典来统计数量,可以这样做:

count_dict = {}
for item in my_list:
    count_dict.setdefault(item, 0)
    count_dict[item] += 1

然后找到最大值,可以这样:

maxi = max(count_dict[item] for item in count_dict)

接下来只需要找出那些特定数量的元素就可以了。

除了使用普通字典,你还可以用 collections.defaultdict

from collections import defaultdict
count_dict = defaultdict(int)
for item in my_list:
    count_dict[item] += 1

其他的思路都是一样的。

如果你想把字符串连接在一起打印出来,可以这样做:

print("Most Common:", ", ".join([item for item in count_dict if count_dict[item] == maxi]))
# Most Common: duck, goose

撰写回答