【问题标题】:A pythonic method to find the item with most occurrences and its number of occurrences in a list in python? [duplicate]一种在python列表中查找出现次数最多的项目及其出现次数的pythonic方法? [复制]
【发布时间】:2020-11-10 10:43:34
【问题描述】:

假设我有一个数组

arr = [1,2,2,3,4,5]

查找出现次数最多的项目以及它在列表中出现多少次的最有效和“pythonic”方式是什么?

【问题讨论】:

  • 使用collections.Counter

标签: python


【解决方案1】:

查找出现次数最多的项目以及它在列表中出现多少次的最有效和“pythonic”方式是什么?

使用Collections.Counter 获取每个元素的dict,并使用most_common 查找出现次数最多的元素。试试这个:

import collections

arr = [1,2,3,4,5,3]
counts = collections.Counter(arr)

print("Counter:", counts)
# counts.most_common()   # Returns all unique items and their counts
print("Most Occurred:", counts.most_common(1)[0][0])  # Returns the highest occurring item

输出:

Counter: Counter({3: 2, 1: 1, 2: 1, 4: 1, 5: 1})
Most Occurred: 3

【讨论】:

  • 您好,感谢您的回答。当我运行它时,我得到:Counter({2: 2, 1: 1, 3: 1})。我将如何继续将模式的出现次数(即 2)存储在变量中。
  • 我也更新了。
猜你喜欢
  • 2011-10-22
  • 2016-03-30
  • 2020-04-19
  • 2015-12-11
  • 2011-10-16
  • 2012-07-31
  • 1970-01-01
  • 2010-11-11
相关资源
最近更新 更多