gpt4 book ai didi

python - 在 for 循环中后退迭代

转载 作者:IT老高 更新时间:2023-10-28 20:32:17 27 4
gpt4 key购买 nike

所以我想做这样的事情:

for i in range(5):
print(i);
if(condition==true):
i=i-1;

但是,无论出于何种原因,即使我正在递减 i,循环似乎也没有注意到。有没有办法重复迭代?

最佳答案

Python 中的

for 循环始终向前。如果希望能够向后移动,则必须使用不同的机制,例如 while:

i = 0
while i < 5:
print(i)
if condition:
i=i-1
i += 1

甚至更好:

i = 0
while i < 5:
print(i)
if condition:
do_something()
# don't increment here, so we stay on the same value for i
else:
# only increment in the case where we're not "moving backwards"
i += 1

关于python - 在 for 循环中后退迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14374181/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com