python - 将具有偶数个条目的列表分成两半是无效索引
问题描述
我有一个列表,如果它有偶数个值,我想找到两个中间条目的中点。我这样做是这样的:
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
解决方案
与 Python 2 不同,在 Python 3 中,/
运算符总是返回一个浮点数,即使操作数都是整数。您应该使用地板除法运算符//
,因为列表索引必须是整数:
l = (points[len(points) // 2][1] + points[len(points) // 2 + 1][1]) / 2
推荐阅读
- ruby - Ubuntu 20.0LTS 上的 AWS CodeDeploy-Agenten,Ruby 错误
- java - Micronaut(Gradle 和 Java)- 启用安全性后无法访问 Swagger 集成视图
- java - 带过滤器的 IntStream 迭代函数
- mysql - 在sql中查找对象是否在不到1分钟的时间内两次获得记录器
- graphql - 找不到模块“graphql/tsutils/Maybe”或其相应的类型声明
- android - 当应用失去焦点时破坏活动
- python - Plotly:如何设置零线不透明度?
- javascript - 如何通过自定义装饰器记录@Input/@Output 值的值
- node.js - 无法通过公司代理进行 HTTPS SOAP 调用 - getaddrinfo ENOTFOUND
- sql - 比较日期时,相同的工作查询不起作用