Python求中值函数误差

Python Finding the median function error

任何人都可以向我解释为什么这不起作用吗?我收到的错误消息是:TypeError: list indices must be integers or slice, not float.

def median(lst):
    s = sorted(lst)
    l = len(lst)/2
    if len(lst) % 2 == 0:
        print((s[l] + s[l-1])/2.0)
    else:
        print(s[l])
median([3,3,5,6,7,8,1])

如果 len(lst) 为奇数,则 l 变为浮点数。

有趣的是,您编写的代码可能在 Python 2 中有效,因为如果分子和分母都是整数,它使用整数除法。

然而在Python中默认使用3真除法。

有关详细信息,请参阅:In Python 2, what is the difference between '/' and '//' when used for division? and https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator

您在计算 l

时犯了错误

使用运算符除法 / returns 实际除法即浮点值,而 // returns 仅商即整数

因此

你应该计算l如下

l = len(lst) // 2

或使用

l 转换为 int
l  = int(l)