【问题标题】:Most occurring element in a list [duplicate]列表中出现次数最多的元素[重复]
【发布时间】:2020-01-26 02:09:39
【问题描述】:

有没有办法将列表中出现次数最多的元素的列表输出到列表中,或者如果出现平局,则将所有出现次数最多的元素输出到列表中?

我想在不导入任何类的情况下解决这个问题!

例如,[5,4,3] 将输出 [5,4,3]。

[5,4,4,5] 将输出 [5,4]

我已经尝试过,max(set(list), key=list.count) 但对领带确实不起作用。

到目前为止我的工作:

test = ['test1', 'test2', 'test3']
dict = {}

for elements in test:
    if elements in dict:
        dict[elements] += 1
    else:
        dict[elements] = 0
        dict[elements] += 1

print (dict)

【问题讨论】:

  • 使用Counter
  • @ArkistarvhKltzuonstev 是的,已编辑!
  • 您的第二个解决方案有什么问题?

标签: python list


【解决方案1】:

您可以使用collections.Counter,找到最大计数,然后保留最大计数:

from collections import Counter

counts = Counter([5, 4, 4, 5, 3])

max_count = max(counts.values())
result = [k for k, count in counts.items() if count == max_count]

print(result)

输出

[5, 4]

你可以用一个简单的字典代替 Counter:

data = [5, 4, 4, 5, 3]
counts = {}

for e in data:
    counts[e] = counts.get(e, 0) + 1

max_count = max(counts.values())
result = [k for k, count in counts.items() if count == max_count]

print(result)

【讨论】:

  • 这行得通,但我正在寻找一种没有进口的方法。谢谢!
  • @user145682 更新了答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-24
  • 1970-01-01
  • 2019-03-24
  • 2013-05-18
  • 2011-10-22
相关资源
最近更新 更多