如何防止for循环在Python中推进?

时间:2011-08-19 16:41:24

标签: python for-loop

如果满足某个条件,是否可以阻止for循环进入列表/迭代器中的下一个值?

lst = list('abcde')
for alphabet in lst:
  if some_condition:
     # somehow prevent the for loop from advancing so that in the
     # next iteration, the value of alphabet remains the same as it is now
  # do something

4 个答案:

答案 0 :(得分:8)

您似乎想要的是嵌套的while循环。只有当while循环退出时,for循环才会继续下一个值。

alphabet = "abcdefghijklmnopqrstuvwxyz"
for letter in alphabet:
  while some_condition:
     # do something

答案 1 :(得分:4)

您可以使用break立即退出循环,或continue跳转到循环的下一次迭代。有关详细信息,请参阅http://docs.python.org/tutorial/controlflow.html

编辑:实际上,经过仔细检查,你所寻找的是一个相当奇怪的情况。你考虑过像

这样的东西吗?
lst = list('abcde')
specialcase = ""
for alphabet in lst:
  if specialcase != "":
       alphabet = specialcase
       specialcase = ""
  elif some_condition:
     # somehow prevent the for loop from advancing so that in the
     # next iteration, the value of alphabet remains the same as it is now
     specialcase = alphabet
  #do something

你必须修改它以适合你的特定情况,但它应该给你这个想法。

答案 2 :(得分:2)

手动循环但小心不要卡住

>>> i = 0
>>> j = 0
>>> abc = 'abcdefg'
>>> while i < len(abc):
...     print abc[i]
...     if abc[i] == 'd' and j == 0:
...         print 'again'
...         j = 1
...         i -= 1
...     i += 1
a
b
c
d
again
d
e
f
g

另一个人使用for但是有点像黑客

>>> labc
4: ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> flag
5: True
>>> for i in labc:
...     print i
...     if i == 'd' and flag:
...         flag = False
...         labc[labc.index(i):labc.index(i)] = [i]
a
b
c
d
d
e
f
g

答案 3 :(得分:0)

我认为你不能(或应该)使用常规的list-iterator来做这件事。您可能希望将此视为工作队列的情况并使用while循环:

work_stack = list('abcde')

prev_item = ''
while work_stack:
    item = work_stack.pop(0)
    print item
    if prev_item=='a' and item == 'b':
        work_stack.insert(0,item)
    prev_item = item