[英]Python: Changing the conditions of a 'for' loop
I am attempting to loop through a set of points, and if certain conditions are met, add in another point inbetween the current point and the next one. 我试图遍历一组点,如果满足某些条件,请在当前点和下一个点之间添加另一个点。 I then want to start the loop again, running over both the old and new points. 然后,我想再次开始循环,遍历新旧点。 For example: 例如:
for i in range(3)
i
doesn't meet a certain set of conditions, add in a new point after i
.This will change the range to range(4)
. 如果i
不满足特定条件,请在i
之后添加一个新点,这将范围更改为range(4)
。 End the loop, and restart with for i in range(4)
. 结束循环,并使用for i in range(4)
重新开始。 range(3)
. 如果我确实满足条件,则继续在range(3)
。 If i
reaches the end without having to add in a new point, exit the loop and continue with the rest of the code. 如果i
到达终点而不必添加新点,则退出循环并继续其余代码。 I have tried a variety of methods, but I can't get anything to work. 我尝试了多种方法,但是我什么都做不了。 My understanding would be that it is along the lines of: 我的理解是,它遵循以下原则:
b = 3
for i in range(b):
if (i meets conditions):
pass
else:
b = b+1
"retry entire loop with new b"
I have also tried using a while loop, however I can't see how I could get this to start again at the first point, should a new point be added in. 我也尝试过使用while循环,但是如果添加新的点,我看不到如何在第一点重新开始。
I might be missing something simple, but I just can't see the solution to this. 我可能缺少一些简单的东西,但是我看不到解决方案。
Thanks for the help! 谢谢您的帮助!
You'll need to use a recursive function for this: 您需要为此使用递归函数:
def func(l):
for i, el in enumerate(l):
if (el match the conditions):
l.insert(i+1, something)
return func(l)
return l
l = [1, 2, 3]
result = func(l)
Or use a while loop: 或使用while循环:
l = [1, 2, 3]
while True:
i = 0
if i >= len(l):
break
if (l[i] match the condition):
l.insert(i+1, something)
i = 0
else:
i += 1
b = 3
found = False
while True:
for i in range(b):
if (i meets conditions):
found = True
break # Done - breaks out
if found:
break
else:
b += 1
Using a while loop... 使用while循环...
has_change = True
b = 3
while has_change:
new_b = b
for i in range(b):
if (i meets conditions):
pass
else:
new_b = b+1
break
changed = new_b != b
Use a while loop to trigger new for loops 使用while循环触发新的for循环
b = 3
criteria_met = False
while (criteria_met == False):
for i in range(b):
if (i == 1):
b = b+1
criteria_met = True
break
print b
As a side note here, be careful for infinite loops when using loops like this. 作为此处的附带说明,在使用像这样的循环时要小心无限循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.