【发布时间】:2020-11-10 10:43:34
【问题描述】:
假设我有一个数组
arr = [1,2,2,3,4,5]
查找出现次数最多的项目以及它在列表中出现多少次的最有效和“pythonic”方式是什么?
【问题讨论】:
-
使用
collections.Counter
标签: python
假设我有一个数组
arr = [1,2,2,3,4,5]
查找出现次数最多的项目以及它在列表中出现多少次的最有效和“pythonic”方式是什么?
【问题讨论】:
collections.Counter
标签: python
查找出现次数最多的项目以及它在列表中出现多少次的最有效和“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)存储在变量中。