函数计数中值(python)

2024-04-24 19:02:41 发布

您现在位置:Python中文网/ 问答频道 /正文

def median(lista):
    if len(lista) % 2 == 1:
        float(x) = (len(lista))/(2)
        lista2 = sorted(lista)
        y = x + 0.5
        return lista2[y]
    else:
        x = len(lista)
        total = 0
        for i in lista:
            total += i
        return total/x

这个函数有什么问题?显示错误

File "python", line 3 SyntaxError: can't assign to function call

我知道你可以告诉我如何用100万种不同的方式编写这个函数,但是你能解释一下为什么这个确切的版本不起作用吗?你知道吗

提前谢谢。你知道吗


Tags: 函数inforlenreturnifdef错误
3条回答

你的功能有几个问题:

def median(lista):
    if len(lista) % 2 == 1:
        float(x) = (len(lista))/(2)  # you assign to a function?
        lista2 = sorted(lista)
        y = x + 0.5                  # y is now a float
        return lista2[y]             # accessing the float index?
    else:                            # here you calculate the average
        x = len(lista)
        total = 0
        for i in lista:
            total += i
        return total/x

偶数列表的中位数是而不是平均值。它是中间两个元素的平均值。你知道吗

您只需编写以下函数:

def median(lista):
    listb = sorted(lista)
    n_lista = len(lista)
    half = n_lista//2
    if n_lista % 2:
        return lista[half]
    else:
        return 0.5*(lista[half-1]+lista[half])

float转换应用于赋值float(x) = (len(lista))/(2)的错误一侧。像x = float((len(lista))/(2))那样把它移到另一个位置,代码就可以工作了

我认为你想把一半的长度作为浮点值,对吗?你知道吗

如果是这样,您必须在功能上需要的地方应用float转换,而不是把它当作语言修饰语:

x = float(len(lista))/(2)

或者简单地用一个float常量强制这个结果:

x = len(lista) / 2.0

相关问题 更多 >