如何在Python中生成多种模式?

hay*_*isa 3 python mode

基本上我只需要弄清楚如何从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
Run Code Online (Sandbox Code Playgroud)

但是,不是在"所有值只显示一次"或"列表有多种模式"中返回字符串,我希望它返回它引用的实际整数?

nne*_*neo 9

制作一个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]
Run Code Online (Sandbox Code Playgroud)