2024-04-19 09:02:01 发布
网友
如何在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有^{}:
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
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-2.x一起工作):
def median(lst): n = len(lst) s = sorted(lst) return (sum(s[n//2-1:n//2+1])/2.0, s[n//2])[n % 2] if n else None
>>> median([-5, -5, -3, -4, 0, -1]) -3.5
^{}:
>>> from numpy import median >>> median([1, -4, -1, -1, 1, -3]) -1.0
对于python-3.x,使用^{}:
>>> from statistics import median >>> median([5, 2, 3, 8, 9, -2]) 4.0
sorted()函数对此非常有用。使用排序函数 要对列表排序,只需返回中间值(或平均两个中间值 值(如果列表包含偶数个元素)。
def median(lst): sortedLst = sorted(lst) lstLen = len(lst) index = (lstLen - 1) // 2 if (lstLen % 2): return sortedLst[index] else: return (sortedLst[index] + sortedLst[index + 1])/2.0
Python 3.4有^{} :
用法:
它对类型也非常小心:
(与python-2.x一起工作):
^{} :
对于python-3.x,使用^{} :
sorted()函数对此非常有用。使用排序函数 要对列表排序,只需返回中间值(或平均两个中间值 值(如果列表包含偶数个元素)。
相关问题 更多 >
编程相关推荐