如何在Python中找到列表的中位数?该列表可以是任何大小,并且不能保证数字以任何特定顺序排列.
How do you find the median of a list in Python? The list can be of any size and the numbers are not guaranteed to be in any particular order.
如果列表包含偶数个元素,则该函数应返回中间两个元素的平均值.
If the list contains an even number of elements, the function should return the average of the middle two.
以下是一些示例(出于显示目的排序):
Here are some examples (sorted for display purposes):
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 :
Python 3.4 has 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')更多推荐
在Python中查找列表的中位数
发布评论