3

基本上我只需要弄清楚如何从 Python 中的列表中生成模式(出现频率最高的数字),无论该列表是否具有多种模式?

像这样的东西:

def print_mode (thelist):
  counts = {}
  for item in thelist:
    counts [item] = counts.get (item, 0) + 1
  maxcount = 0
  maxitem = None
  for k, v in counts.items ():
    if v > maxcount:
      maxitem = k
      maxcount = v
  if maxcount == 1:
    print "All values only appear once"
  if counts.values().count (maxcount) > 1:
    print "List has multiple modes"
  else:
    print "Mode of list:", maxitem

但不是在“所有值只出现一次”或“列表有多种模式”中返回字符串,而是希望它返回它引用的实际整数?

4

3 回答 3

12

制作 a Counter,然后挑选出最常见的元素:

from collections import Counter
from itertools import groupby

l = [1,2,3,3,3,4,4,4,5,5,6,6,6]

# group most_common output by frequency
freqs = groupby(Counter(l).most_common(), lambda x:x[1])
# pick off the first group (highest frequency)
print([val for val,count in next(freqs)[1]])
# prints [3, 4, 6]
于 2013-02-10T01:17:11.217 回答
0

在 python 3.8 的统计模块中新增了一个函数:

import statistics as s
print("mode(s): ",s.multimode([1,1,2,2]))

输出:模式:[1, 2]

于 2020-08-10T19:44:46.767 回答
0
def mode(arr):

if len(arr) == 0:
    return []

frequencies = {}

for num in arr:
    frequencies[num] = frequencies.get(num,0) + 1

mode = max([value for value in frequencies.values()])

modes = []

for key in frequencies.keys():
    if frequencies[key] == mode:
        modes.append(key)

return modes

此代码可以处理任何列表。确保列表的元素是数字。

于 2020-11-24T13:43:40.197 回答