python - Python 中列表的中位数

标签 python list

我查找了与这些类似的帖子,人们发布的示例向我抛出了与我自己的版本相同的错误。我不断收到错误“列表索引必须是整数,而不是 float 。”我相信获得中位数背后的逻辑很好,但我不知道如何解决这个问题。我知道发生这种情况是因为 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))

最佳答案

在 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 - Python 中列表的中位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37706539/

相关文章:

python - django 唯一对象(不是唯一字段)?

python - 如何将数据从一个类传递给另一个函数(在 HTMLParser 中)?

java - 使用 List<> 参数重载 Java 函数

python - 列表列表更改意外地反射(reflect)在子列表中

c# - protobuf-net List<>继承反序列化

java - 如何从 linkedhashmap 列表中单独获取 linkedhashmap

python - PyQt5 和 Python 3.6 安装?

python - 添加 hstore 字段后如何创建迁移? (django-hstore 与南方)

Windows 8.1 上的 Python 多处理池仅生成一名工作人员

python - 如何循环检查列表中的所有值是否大于另一个列表中的值?