我查了类似的帖子,人们发布的例子就像我自己的版本一样向我抛出同样的错误.我一直得到错误"列表索引必须是整数,而不是浮点数." 我相信我在获得中位数背后的逻辑很好,但我无法弄清楚如何解决这个问题.我知道这是因为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))
Run Code Online (Sandbox Code Playgroud)
我尝试这样做来修复它但仍然出现同样的错误:
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))
Run Code Online (Sandbox Code Playgroud)
异常是由Python 3.x /上返回的运算符引起的float.//在计算索引时使用整数除法:
>>> 2 / 1
2.0
>>> 2 // 1
2
Run Code Online (Sandbox Code Playgroud)
在 python 版本 3 中做的更好的方法是使用模块统计信息
import statistics
items = [1, 2, 3, 6, 8]
statistics.median(items)
Run Code Online (Sandbox Code Playgroud)
如果你想要一个功能,试试这个。
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)
Run Code Online (Sandbox Code Playgroud)
您还可以使用我经常使用的 numpy.median():
import numpy
def median(l):
return numpy.median(numpy.array(l))
Run Code Online (Sandbox Code Playgroud)