Python 停留在 For 循环中的元素上
Python Stay on Element In For Loop
我想知道如何以某种方式停留在一个元素上,直到 for 循环中的下一个循环周期。这是一个代码示例:
for element in numbers:
try:
...
except:
# It should stay on this element for the next time
pass
例如,我有
numbers = ['apple', 'banana', 'peach']
现在我以 Banana 元素为例,如果出现该错误,它应该一直停留在 banana 上直到下一个周期,因此预期输出将是:apple, banana (error), banana (现在它再次尝试),桃子。
据我所知,使用常规 for 循环是不可能的。直接控制迭代变量也可以得到类似的东西:
i = 0
while i < len(numbers):
try:
# Do work
numbers[i] ....
i += 1
except:
# Don't increment i
pass
请小心,因为如果“banana”永远不会成功,您可能会陷入无限循环。
使用 while 循环迭代索引:
i = 0
while i < len(numbers):
element = numbers[i]
try:
...
i+=1
except:
# It should stay on this element for the next time
pass
您可以在 for 循环中使用一个简单的 while 循环来做到这一点:
for element in numbers:
while True:
try:
...
break # Success; break out of the while to the next element.
except:
# It should stay on this element for the next time
pass
您可以在 for
中放置一个 while
以继续处理该元素,直到您满意为止。这可能会导致无限循环,因此请明智地编写代码。
numbers = ['apple', 'banana', 'peach']
i_hate_bananas = True
for element in numbers:
while True:
try:
if i_hate_bananas and element == 'banana':
raise ValueError(f'{element}, yuck')
print("I like", element)
break
except ValueError as e:
print(e)
i_hate_bananas = False
print('done')
这可能比只有一个 while
并将索引器递增到 numbers
更好,因为它适用于迭代,因此适用于任何可迭代对象。
我想知道如何以某种方式停留在一个元素上,直到 for 循环中的下一个循环周期。这是一个代码示例:
for element in numbers:
try:
...
except:
# It should stay on this element for the next time
pass
例如,我有
numbers = ['apple', 'banana', 'peach']
现在我以 Banana 元素为例,如果出现该错误,它应该一直停留在 banana 上直到下一个周期,因此预期输出将是:apple, banana (error), banana (现在它再次尝试),桃子。
据我所知,使用常规 for 循环是不可能的。直接控制迭代变量也可以得到类似的东西:
i = 0
while i < len(numbers):
try:
# Do work
numbers[i] ....
i += 1
except:
# Don't increment i
pass
请小心,因为如果“banana”永远不会成功,您可能会陷入无限循环。
使用 while 循环迭代索引:
i = 0
while i < len(numbers):
element = numbers[i]
try:
...
i+=1
except:
# It should stay on this element for the next time
pass
您可以在 for 循环中使用一个简单的 while 循环来做到这一点:
for element in numbers:
while True:
try:
...
break # Success; break out of the while to the next element.
except:
# It should stay on this element for the next time
pass
您可以在 for
中放置一个 while
以继续处理该元素,直到您满意为止。这可能会导致无限循环,因此请明智地编写代码。
numbers = ['apple', 'banana', 'peach']
i_hate_bananas = True
for element in numbers:
while True:
try:
if i_hate_bananas and element == 'banana':
raise ValueError(f'{element}, yuck')
print("I like", element)
break
except ValueError as e:
print(e)
i_hate_bananas = False
print('done')
这可能比只有一个 while
并将索引器递增到 numbers
更好,因为它适用于迭代,因此适用于任何可迭代对象。