Python |中位数是排序的数字序列中的中间数字

时间:2015-07-31 18:07:14

标签: python

def median (lst):
    lst.sort()
    if len(lst) % 2==0:
        print  sum(lst[len(lst)-1:len(lst)])
    else:
        print sum(len(lst)/2)

median([4, 5, 5, 4,2,5,6,9,10])

错误发生在:print sum(len(lst)/2)

TypeError: 'int' object is not iterable

为什么不起作用?

2 个答案:

答案 0 :(得分:3)

您需要将print sum(len(lst)/2)替换为:

print lst[len(lst) / 2]

因为你想要的是采取列表的中间元素。错误的是sum不在数字列表上,而是在数字上。如果您想使用总和表示法,您可以执行以下操作:

print sum([lst[len(lst)//2]])

表示将数字包含在列表中。

答案 1 :(得分:0)

Why not use the built-in function?

>>> from statistics import median
>>> median([1, 3, 5])

above taken from this post: Median code explanation

or, if you must do it the hard way:

def median(a):
ordered = sorted(a)
length = len(a)
return float((ordered[length/2] + ordered[-(length+1)/2]))/2

Also taken from the same post...

相关问题