在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(*arg):
order(arg)
numArg = len(arg)
half = int(numArg/2)
if numArg/2 ==half:
print((arg[half-1]+arg[half])/2)
else:
print(int(arg[half]))
def order(tup):
ordered = [tup[i] for i in range(len(tup))]
test(ordered)
while(test(ordered)):
test(ordered)
print(ordered)
def test(ordered):
whileloop = 0
for i in range(len(ordered)-1):
print(i)
if (ordered[i]>ordered[i+1]):
print(str(ordered[i]) + ' is greater than ' + str(ordered[i+1]))
original = ordered[i+1]
ordered[i+1]=ordered[i]
ordered[i]=original
whileloop = 1 #run the loop again if you had to switch values
return whileloop
其他回答
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')
import numpy as np
def get_median(xs):
mid = len(xs) // 2 # Take the mid of the list
if len(xs) % 2 == 1: # check if the len of list is odd
return sorted(xs)[mid] #if true then mid will be median after sorting
else:
#return 0.5 * sum(sorted(xs)[mid - 1:mid + 1])
return 0.5 * np.sum(sorted(xs)[mid - 1:mid + 1]) #if false take the avg of mid
print(get_median([7, 7, 3, 1, 4, 5]))
print(get_median([1,2,3, 4,5]))
如果您需要关于列表分布的额外信息,百分位数方法可能会很有用。中位数对应于列表的第50个百分位数:
import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9])
median_value = np.percentile(a, 50) # return 50th percentile
print median_value
def median(array):
"""Calculate median of the given list.
"""
# TODO: use statistics.median in Python 3
array = sorted(array)
half, odd = divmod(len(array), 2)
if odd:
return array[half]
return (array[half - 1] + array[half]) / 2.0
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])