首页 > 解决方案 > 将具有偶数个条目的列表分成两半是无效索引

问题描述

我有一个列表,如果它有偶数个值,我想找到两个中间条目的中点。我这样做是这样的:

    if len(points) % 2 == 0:
        l = (points[len(points)/2][1] + points[len(points)/2 + 1][1])/2

但是,我收到一条错误消息:

TypeError: list indices must be integers or slices, not float

标签: pythonpython-3.x

解决方案


与 Python 2 不同,在 Python 3 中,/运算符总是返回一个浮点数,即使操作数都是整数。您应该使用地板除法运算符//,因为列表索引必须是整数:

l = (points[len(points) // 2][1] + points[len(points) // 2 + 1][1]) / 2

推荐阅读