Python中列表的中值

2024-10-02 00:20:07 发布

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

我已经查找了与这些类似的帖子,人们发布的示例也向我抛出了与我自己的版本相同的错误。我一直得到一个错误“列表索引必须是整数,而不是浮点数”,我相信我得到中值的逻辑是正确的,但我不知道如何避开这个问题。我知道这是因为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))

Tags: 列表lenreturnifdef错误floatsort
3条回答

关于解决浮动问题还有其他一些答案。不过,要回答你的问题,甚至长度列表,从谷歌:

The median is also the number that is halfway into the set. To find the median, the data should be arranged in order from least to greatest. If there is an even number of items in the data set, then the median is found by taking the mean (average) of the two middlemost numbers.

所以您需要做(list[len/2]*list[(len/2)-1])/2(0个索引数组减1,1个索引数组加1)

在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 3.x上返回float/运算符引起的。在计算索引时,请使用整数除法//

>>> 2 / 1
2.0
>>> 2 // 1
2

相关问题 更多 >

    热门问题