python - 如何制作“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]
解决方案
在这种情况下,我会说你不需要一路走到n
.
也许你应该将你的 for 循环更改为for c in range(n-1):
推荐阅读
- java - 我们可以在 Spring Boot 中将 csv 文件写入 S3 而不在本地创建文件吗?
- javascript - 角度 AOT 中的动态模板 URL
- php - Ajax resquest响应在php mysql中总是等于零
- python - 使用 Python 自动化 .exe 程序
- sql-server - SSIS Oracle Source 未正确提取 Unicode 字符
- kaggle - 为什么我的比赛结果从我在 Kaggle 的个人资料页面中消失了?
- ios - 如何在使用 UIKitForMac 构建的 mac 应用程序中从 UITableViews 中删除蓝色边框/轮廓?
- apache-camel - 骆驼:通过聚合丰富民意调查
- java - XML 验证似乎忽略了一些 XSD 元素
- javascript - 在reduce函数之后返回一个对象