python - 如何处理python中的“List out of index”错误?
问题描述
我有列表socpu
,我正在以这种方式从该列表中计算另一个列表:
Import logging
socpu = [12,23,34,45,43,32,21,23,44,32,11,22,55,33]
try:
chargeAndDischarge = [socpu[i+1]-socpu[i] for i in range(len(socpu))]
except Exception as e:
logging.exception("Something awful happened!")
print(e)
print(chargeAndDischarge)
在这个程序中,我使用的是 socpu[i+1] 最终会List out of index
出错,这就是为什么我把它放在try and except
块中但是有没有其他方法呢?另外,即使将其放入Try and except
块中,也会出现错误:
UnboundLocalError: local variable 'chargeAndDischarge' referenced before assignment
预期答案:
chargeAndDischarge = [11,11,11,-2,-11,-11,2,21,-12,-21,11,33,-22]
谁能帮忙?
解决方案
只需将其更改为:
chargeAndDischarge = [socpu[i+1]-socpu[i] for i in range(len(socpu)-1)]
差异列表的长度需要比原始列表的长度小一。1
从长度中减去即可完成此操作。
推荐阅读
- javascript - 在 ajax 响应 wordpress 插件中获取 0
- jquery - jQuery自动完成minLength不起作用
- javascript - 自动完成移除边框
- cvxpy - 使用 DCP 规则集编写 Dirichlet 对数似然
- node.js - 无法从 Node.js 中的异步函数返回值,但控制台会打印值
- django - 在 Django 模型中存储问卷的答案
- javascript - 为我的 jQuery 创建循环时遇到问题
- python - 在 php 中构建 webhook 发送者,在 python 中构建接收者
- python - 如何使用 Tkinter 显示倒数计时器?
- asp.net-mvc - Asp-action 编辑未从剃刀页面获取数据