python - 我可以得到两种模式(统计)吗?
问题描述
我这里有个错误
import statistics
data=[5, 8, 15, 7, 10, 22, 3, 1, 15,10]
print (statistics.mode(data))
我可以在 Python 中获得两种模式吗?
解决方案
对于一个简单的解决方案和一个简短的列表,您可以使用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
推荐阅读
- python - 如何在不影响性能的情况下使用/导入大型字典?
- python - 来自 io.BytesIO 的 Tell() 方法未返回正确的图像权重
- reactjs - reactjs:错误:找不到 react-redux 上下文值;请确保组件被包裹在一个
- javascript - 根据它们所在的背景显示文本颜色
- javascript - 挂起的回调数量过多:501. React Native - Expo Camera
- javascript - D3.js - 未捕获的类型错误:.enter(...).append(...).merge 不是函数
- python - 为什么我需要在 Heroku 中进行相对导入,但在本地运行时不需要?
- java - 是否可以将 JSON 中缺少的值反序列化为某些默认值?
- angular - 如何将此表示日期的字符串转换为正确的 FireStore 时间戳字段?
- java - java-给处理中的数组赋值