【问题标题】:Without using Counter(), how to find most common element in a list? [closed]不使用 Counter(),如何在列表中找到最常见的元素? [关闭]
【发布时间】:2014-04-11 06:19:34
【问题描述】:

不使用Counter() 类,而是使用普通字典,我如何在列表中找到最常见的元素?

给定的列表是:

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

我希望输出是这样的

most_common: duck, goose

其中计数相同的元素如果都是最大值,则都会出现,然后可以将它们输出为字符串而不是自己的列表。

【问题讨论】:

  • 应该可以通过多种方式实现。你能分享一下你的想法吗?
  • stackoverflow.com/a/22442314/2301450。而且 Counter 不是一个函数,它是一个类。
  • 你为什么不想使用 Counter?
  • @JayanthKoushik 显然是某种功课
  • 我编辑得够好吗?

标签: python string list counter


【解决方案1】:

像这样使用普通字典来收集计数

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)

现在只需查找具有特定计数的元素

print([item for item in count_dict if count_dict[item] == maxi])
# ['goose', 'duck']

您也可以使用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

【讨论】:

  • 你可以做 max(counter, key=lambda x: counter[x]) 来找到元素。
  • 当然,这不会找到所有最大值。
  • 不要调用你的字典counter。它可能会使 OP 感到困惑。
  • @devnull 对,更新了 :)
  • @thefourtheye 谢谢!所以我让它正确计数(maxi),但打印功能给了我一个无效的语法错误。我知道我的问题是穴居人会问的,但我只用 Python 编程了几个月。感谢在我学习这门新语言时获得的所有帮助!
【解决方案2】:

首先,使用预定义的类名来对象是一个坏习惯,您在问题中使用了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}
>>> 

【讨论】:

  • @NiklasB。谢谢,更新答案。
猜你喜欢
  • 2012-11-12
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 2010-12-03
相关资源
最近更新 更多