假设我有一个 for 循环:
for i in range(1,10):
if i is 5:
i = 7
i
如果满足某些条件,我想更改。我试过这个但没有用。我该怎么做?
对于您的特定示例,这将起作用:
for i in range(1, 10):
if i in (5, 6):
continue
while
但是,使用循环可能会更好:
i = 1
while i < 10:
if i == 5:
i = 7
# other code
i += 1
循环在每次迭代开始时将变量(在这种情况下)分配给列表/可迭代中的下一个元素for
。i
这意味着无论你在循环内做什么,i
都会成为下一个元素。while
循环没有这样的限制。
关于为什么问题中的循环不能按预期工作的更多背景知识。
一个循环
for i in iterable:
# some code with i
基本上是一个简写
iterator = iter(iterable)
while True:
try:
i = next(iterator)
except StopIteration:
break
# some code with i
因此,for
循环从一个由可迭代对象构造的迭代器中提取值,并自动识别该迭代器何时耗尽并停止。
如您所见,在循环的每次迭代中while
i被重新分配,因此i
无论您在部件中发出任何其他重新分配,都将覆盖的值# some code with i
。
出于这个原因,for
Python 中的循环不适合对循环变量进行永久更改,您应该while
改用循环,正如 Volatility 的回答中已经证明的那样。
这个概念在 C 世界中并不罕见,但应尽可能避免。尽管如此,这就是我实现它的方式,以一种我觉得很清楚发生了什么的方式。然后,您可以将向前跳过的逻辑放在循环内的任何位置的索引中,读者会知道要注意跳过变量,而在某个深处嵌入 i=7 很容易被遗漏:
skip = 0
for i in range(1,10):
if skip:
skip -= 1
continue
if i=5:
skip = 2
<other stuff>
简单的想法是 i 在每次迭代后获取一个值,而不管它在循环内分配给什么,因为循环在迭代结束时递增迭代变量,并且由于 i 的值在循环内声明,它只是被覆盖. 您可能想将 i 分配给另一个变量并对其进行更改。例如,
for i in range(1,10):
if i == 5:
u = 7
然后您可以继续使用循环内的“break”来中断循环,以防止进一步的迭代,因为它满足了所需的条件。
正如timgeb解释的那样,您使用的索引每次都在 for 循环开始时分配一个新值,我发现工作的方式是使用另一个索引。
例如,这是您的原始代码:
for i in range(1,10):
if i is 5:
i = 7
您可以改用这个:
i = 1
j = i
for i in range(1,10):
i = j
j += 1
if i == 5:
j = 7
此外,如果您在 for 循环中修改列表中的元素,则可能还需要在每个循环结束时将范围更新为 range(len(list)) 如果您在其中添加或删除了元素。我这样做的方式就像分配另一个索引来跟踪它。
list1 = [5,10,15,20,25,30,35,40,45,50]
i = 0
j = i
k = range(len(list1))
for i in k:
i = j
j += 1
if i == 5:
j = 7
if list1[i] == 20:
list1.append(int(100))
# suppose you remove or add some elements in the list at here,
# so now the length of the list has changed
k = range(len(list1))
# we use the range function to update the length of the list again at here
# and save it in the variable k
但是,使用 while 循环代替会更方便。无论如何,我希望这会有所帮助。