在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中如何找到列表的中值?列表可以是任意大小的,并且数字不保证是任何特定的顺序。
如果列表包含偶数个元素,则函数应返回中间两个元素的平均值。
以下是一些例子(为了便于展示,进行了排序):
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
当前回答
函数值:
def median(d):
d=np.sort(d)
n2=int(len(d)/2)
r=n2%2
if (r==0):
med=d[n2]
else:
med=(d[n2] + d[n2+1]) / 2
return med
其他回答
函数值:
def median(d):
d=np.sort(d)
n2=int(len(d)/2)
r=n2%2
if (r==0):
med=d[n2]
else:
med=(d[n2] + d[n2+1]) / 2
return med
Python 3.4有statistics.median:
返回数值数据的中位数(中间值)。 当数据点数为奇数时,返回中间的数据点。 当数据点数为偶数时,通过取两个中间值的平均值来插值中位数: >>>中位数([1,3,5]) 3. >>>中位数([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')
更普遍的中位数(和百分位数)方法是:
def get_percentile(data, percentile):
# Get the number of observations
cnt=len(data)
# Sort the list
data=sorted(data)
# Determine the split point
i=(cnt-1)*percentile
# Find the `floor` of the split point
diff=i-int(i)
# Return the weighted average of the value above and below the split point
return data[int(i)]*(1-diff)+data[int(i)+1]*(diff)
# Data
data=[1,2,3,4,5]
# For the median
print(get_percentile(data=data, percentile=.50))
# > 3
print(get_percentile(data=data, percentile=.75))
# > 4
# Note the weighted average difference when an int is not returned by the percentile
print(get_percentile(data=data, percentile=.51))
# > 3.04
def median(array):
if len(array) < 1:
return(None)
if len(array) % 2 == 0:
median = (array[len(array)//2-1: len(array)//2+1])
return sum(median) / len(median)
else:
return(array[len(array)//2])
我所做的是:
def median(a):
a = sorted(a)
if len(a) / 2 != int:
return a[len(a) / 2]
else:
return (a[len(a) / 2] + a[(len(a) / 2) - 1]) / 2
解释:基本上,如果列表中的项目数量是奇数,则返回中间的数字,否则,如果你是偶数列表的一半,python会自动舍入较大的数字,这样我们就知道在它之前的数字会少一个(因为我们对它进行了排序),我们可以将默认的较大数字和小于它的数字相加,然后除以2得到中位数。