如何在Python中更改for循环的索引? [英] How to change index of for loop in Python?
本文介绍了如何在Python中更改for循环的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个for循环:
pre $ 是5:
i = 7
我想改变 i
,如果它符合某些条件。我试过,但没有工作。
如何解决这个问题?
解决方案
b
$ b
我在范围内(1,10):
如果我在(5,6):
继续
但是,如果您使用,则循环:
i = 1
while i< 10:
if i == 5:
i = 7
#other code
i + = 1
$ b $ a 为
循环分配一个变量(在本例中为 i
)在每次迭代开始时,列表中的下一个元素/ iterable。这意味着无论你在循环中做什么, i
都将成为下一个元素。 while
循环没有这样的限制。
Suppose I have a for loop:
for i in range(1,10):
if i is 5:
i = 7
I want to change i
if it meets certain condition. I tried this but didn't work.
How do I go about it?
解决方案
For your particular example, this will work:
for i in range(1, 10):
if i in (5, 6):
continue
However, you would probably be better off with a while
loop:
i = 1
while i < 10:
if i == 5:
i = 7
# other code
i += 1
A for
loop assigns a variable (in this case i
) to the next element in the list/iterable at the start of each iteration. This means that no matter what you do inside the loop, i
will become the next element. The while
loop has no such restriction.
这篇关于如何在Python中更改for循环的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文