我已经查找了与这些类似的帖子,人们发布的示例也向我抛出了与我自己的版本相同的错误。我一直得到一个错误“列表索引必须是整数,而不是浮点数”,我相信我得到中值的逻辑是正确的,但我不知道如何避开这个问题。我知道这是因为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))
关于解决浮动问题还有其他一些答案。不过,要回答你的问题,甚至长度列表,从谷歌:
所以您需要做
(list[len/2]*list[(len/2)-1])/2
(0个索引数组减1,1个索引数组加1)在python版本3中,更好的方法是使用模块统计信息
如果你想要一个函数,试试这个。
您还可以使用numpy.median(),我经常使用它:
异常是由在Python 3.x上返回
float
的/
运算符引起的。在计算索引时,请使用整数除法//
:相关问题 更多 >
编程相关推荐