我查找了与这些类似的帖子,人们发布的示例向我抛出了与我自己的版本相同的错误。我不断收到错误“列表索引必须是整数,而不是 float 。”我相信获得中位数背后的逻辑很好,但我不知道如何解决这个问题。我知道发生这种情况是因为 5/2 = 2.5 并且这不是有效的索引,但是在这种情况下我应该如何获得偶数列表的中位数?
我的短代码是:
def median(lst):
lst.sort()
a = len(lst)
if a % 2 == 0:
b = lst[len(lst)/2]
c = lst[(len(lst)/2)-1]
d = (b + c) / 2
return d
if a % 2 > 0:
return lst[len(lst)/2]
myList = [1,8,10,11,5]
myList2 = [10,5,7,2,1,8]
print(median(myList))
print(median(myList2))
我尝试这样做来修复它,但仍然出现相同的错误:
def median(list):
list.sort()
a = float(len(list))
if a % 2 == 0:
b = float(list[len(list)/2])
c = float(list[(len(list)/2)-1])
d = (b + c) / 2.0
return float(d)
if a % 2 > 0:
return float(list[len(list)/2])
myList = [1,8,10,11,5]
myList2 = [10,5,7,2,1,8]
print(median(myList))
print(median(myList2))
最佳答案
在 python 版本 3 中,更好的方法是使用模块统计信息
import statistics
items = [1, 2, 3, 6, 8]
statistics.median(items)
如果你想要一个功能,试试这个。
def median(lst):
quotient, remainder = divmod(len(lst), 2)
if remainder:
return sorted(lst)[quotient]
return float(sum(sorted(lst)[quotient - 1:quotient + 1]) / 2)
您还可以使用我经常使用的 numpy.median() :
import numpy
def median(l):
return numpy.median(numpy.array(l))
关于python - Python 中列表的中位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37706539/