在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 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(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(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])
你可以使用这个列表。排序以避免创建已排序的新列表,并对列表进行排序。
此外,你不应该使用list作为变量名,因为它会掩盖python自己的列表。
def median(l):
half = len(l) // 2
l.sort()
if not len(l) % 2:
return (l[half - 1] + l[half]) / 2.0
return l[half]
当然,你可以使用内置函数,但如果你想创建自己的函数,你可以这样做。这里的技巧是使用~运算符将正数转换为负数。例如~2 -> -3和在Python中使用负in For list将从末尾开始计数。如果你有mid == 2,那么它会从开始取第三个元素,从结束取第三个元素。
def median(data):
data.sort()
mid = len(data) // 2
return (data[mid] + data[~mid]) / 2
def midme(list1):
list1.sort()
if len(list1)%2>0:
x = list1[int((len(list1)/2))]
else:
x = ((list1[int((len(list1)/2))-1])+(list1[int(((len(list1)/2)))]))/2
return x
midme([4,5,1,7,2])