首页 > 解决方案 > 我可以得到两种模式(统计)吗?

问题描述

我这里有个错误

import statistics 
data=[5, 8, 15, 7, 10, 22, 3, 1, 15,10]
print (statistics.mode(data))

我可以在 Python 中获得两种模式吗?

标签: pythonstatistics

解决方案


对于一个简单的解决方案和一个简短的列表,您可以使用collections.Counter

from collections import Counter

top2 = Counter(data).most_common(2)
# [(15, 2), (10, 2)]

要获得第二种模式,您可以执行以下操作:

top2[1][0]
# 10

虽然对于长列表,执行以下操作可能更方便:

n = 2
l = data[:]
for _ in range(1, n+1):
    nth_mode = statistics.mode(l)
    l.remove(nth_mode)

nth_mode
# 10

推荐阅读