python - 在 Python 中查找列表的中位数

如何在 Python 中找到列表的中位数?该列表可以是任意大小,并且不保证数字按任何特定顺序排列。

如果列表包含偶数个元素,则函数应返回中间两个的平均值。

以下是一些示例(为显示目的排序):

median([1]) == 1
median([1, 1]) == 1
median([1, 1, 2, 4]) == 1.5
median([0, 2, 5, 6, 8, 9, 9]) == 6
median([0, 0, 0, 0, 4, 4, 6, 8]) == 2

最佳答案

Python 3.4 有 statistics.median :

Return the median (middle value) of numeric data.

When the number of data points is odd, return the middle data point. When the number of data points is even, the median is interpolated by taking the average of the two middle values:

>>> median([1, 3, 5])
3
>>> median([1, 3, 5, 7])
4.0

用法:

import statistics

items = [6, 1, 8, 2, 3]

statistics.median(items)
#>>> 3

对类型也非常小心:

statistics.median(map(float, items))
#>>> 3.0

from decimal import Decimal
statistics.median(map(Decimal, items))
#>>> Decimal('3')

https://stackoverflow.com/questions/24101524/

相关文章:

python - 多处理。池 : What's the difference between map

linux - 如何在 bash 中检查文件是否创建时间超过 x 时间?

linux - 如何在 bash shell 脚本中包含文件

c - Linux:是否有超时的套接字读取或接收?

python - 在 Python 中注释函数的正确方法是什么?

python - 为什么 4*0.1 的浮点值在 Python 3 中看起来不错,但 3*0.1 不

linux - 如何在命令行中合并图像?

linux - 如何在 Bash 中解析 CSV 文件?

python - 如何模拟在 with 语句中使用的 open (使用 Python 中的 Mock

linux - 有没有办法改变 Unix 中另一个进程的环境变量?