首页 > 解决方案 > 如何制作“for a in range (n) loop”并调用 data[a+1]

问题描述

我遇到了一个问题,我需要使用范围内(n)循环来解决问题。但是有一个条件,有时我可能需要调用 index[a+1] 来满足 if 条件。我意识到这会导致索引超出范围错误,是否有任何解决方案或者我应该实施另一种方法?附上一些代码。

for c in range (n):
  out=enter+width[c]
  if power==cap:
         power-=(width[c])*(height[c])*2+2+enter
  elif power<cap:
         power-=(width[c])*(height[c])*2
  print("Field {:d}: completed. Battery: {:d}.".format(c+1,power))
  if (power-2-out<(cap*0.5)) or (power-(width[c+1])*(height[c+1])-2-out- 
  width[c+1]<(cap*0.5)):
         power=cap
         print("Charging...")
  enter+=width[c]

标签: pythonfor-loop

解决方案


在这种情况下,我会说你不需要一路走到n.

也许你应该将你的 for 循环更改为for c in range(n-1):


推荐阅读