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

时间:2013-02-10 01:06:21

标签: 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

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

3 个答案:

答案 0 :(得分:8)

制作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]

答案 1 :(得分:0)

python 3.8的统计模块的新增功能有一个功能:

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

输出:模式:[1,2]

答案 2 :(得分: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

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