Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何制作;对于范围内的(n)回路“;并调出数据[a&x2B;1]_Python_For Loop - Fatal编程技术网

Python 如何制作;对于范围内的(n)回路“;并调出数据[a&x2B;1]

Python 如何制作;对于范围内的(n)回路“;并调出数据[a&x2B;1],python,for-loop,Python,For Loop,我遇到了一个问题,我需要使用一个in-range(n)循环来解决问题。但有一个条件,有时我可能需要调用索引[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:

我遇到了一个问题,我需要使用一个in-range(n)循环来解决问题。但有一个条件,有时我可能需要调用索引[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]
范围(n)内c的
:
输出=输入+宽度[c]
如果功率=上限:
幂-=(宽[c])*(高[c])*2+2+enter

elif power如果您知道要遍历整个范围,则可以使用列表理解将范围生成为列表,然后遍历该列表:

n = 1234  # Some number
nums = [x for x in range(n)]  # List comprehension generates a full list for the given range

for i, c in enumerate(nums):
    nums[i + 1]  # Access is valid, as long as index is within bounds of list size

在这种情况下,我要说的是,您不需要一直到
n


也许您应该将范围(n-1)中c的for循环更改为

您可以使用try/except块:

范围(n)内c的
:
输出=输入+宽度[c]
如果功率=上限:
幂-=(宽[c])*(高[c])*2+2+enter

elif power我建议将该条件放入代码中,只有在不超出范围时才运行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
  try:
       print("Field {:d}: completed. Battery: {:d}.".format(c+1,power))
  except:
        print("out of range")
  if (power-2-out<(cap*0.5)) :
         power=cap
         print("Charging...")

  elif c + 1 <= len(n) - 1:
    if (power-(width[c+1])*(height[c+1])-2-out-width[c+1]<(cap*0.5)):
               power=cap
               print("Charging...")
  enter+=width[c]
范围(n)内c的
:
输出=输入+宽度[c]
如果功率=上限:
幂-=(宽[c])*(高[c])*2+2+enter

elif power当
c==n
时,您需要什么功能?您当前的代码不一定会导致任何错误-它取决于范围(n-1)内c的
宽度
高度
列表
中的项数
?如果可能,重新定义您的问题,以便您考虑的是上一个元素,而不是下一个元素。在这种情况下,您甚至不需要索引;你只记得你最后看到的价值。不过,我不确定这在这里是否可行。谢谢,我确实研究了try/except方法,但我没有意识到except indexer可以实现。再次感谢。@EdwardLeung如果这解决了您的问题,请勾选此答案左侧的灰色/绿色复选标记,以便所有人都知道问题已经解决。