在Python for循环中,跳过值
time=0
gold=0
level=1
for time in range(100):
gold+=level
if gold>20*level:
level+=1
time+=10
通过这个程序,黄金会被添加,直到达到临界数量,然后需要 20 秒来升级矿井,以便生产更多的黄金。我想跳过循环中的 20 秒(或 20 个步骤)?这在 c++ 中有效,我不知道如何在 python 中做到这一点。
time=0
gold=0
level=1
for time in range(100):
gold+=level
if gold>20*level:
level+=1
time+=10
with this program gold is added until it reaches a critical amount, then it takes 20s to upgrade a mine so it produces more gold. i'd like to skip those 20s (or 20 steps) in the loop? this works in c++, i'm not sure how to do it in python.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要在
range(100)
内执行此操作。for
循环不提供像这样跳过的方法;无论您在循环体中将其更改为什么,time
都将设置为列表中的下一个值。使用while
循环代替,例如Don't do it in
range(100)
. Thefor
loop doesn't offer a way to skip ahead like that;time
will be set to the next value in the list regardless of what you change it to in the body of the loop. Use awhile
loop instead, e.g.time
将在每次循环迭代中不断被覆盖,因此time+=10
将不会达到预期的效果。您可以使用while
和time
变量的显式突变将循环转换回 C 风格循环,或者您也可以设置一个允许向前跳过任意值的迭代器。time
will continually get overwritten each loop iteration, sotime+=10
will not have the desired effect. You can convert the loop back into a C style loop usingwhile
and explicit mutation of thetime
variable or you could be fancy and setup an iterator which allows skipping ahead arbitrary values.您在最后一行对
time
的分配无效。在循环的顶部,time
立即分配给range
生成的下一个值。但为什么这是一个循环,你不能直接进行计算吗?Your assignment to
time
on the last line has no effect. At the top of the loop,time
is immediately assigned to the next value yielded byrange
. But why is this a loop at all, can't you just do the calculations outright?