首页 > 解决方案 > 如何处理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]

谁能帮忙?

标签: pythonlist

解决方案


只需将其更改为:

chargeAndDischarge = [socpu[i+1]-socpu[i] for i in range(len(socpu)-1)]

差异列表的长度需要比原始列表的长度小一。1从长度中减去即可完成此操作。


推荐阅读