开发者

How to prevent a for loop from advancing in Python?

开发者 https://www.devze.com 2023-03-29 14:24 出处:网络
Is it possible to prevent the for loop from proceeding to the next value in the list/iterator if a certain condition is satisfied?

Is it possible to prevent the for loop from proceeding to the next value in the list/iterator if a certain condition is satisfied?

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
  # d开发者_StackOverflowo something


What you seem to want is a nested while loop. Only when the while loop exits will the for loop continue to the next value.

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


You can use break to exit the loop immediately, or continue to skip to the next iteration of the loop. See http://docs.python.org/tutorial/controlflow.html for more details.

Edit: Actually, upon closer inspection, what you're looking for is a rather odd case. Have you considered something like

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

You'll have to modify this to suit your particular situation, but it should give you the idea.


Do the loop manually but be carefull not to be stuck

>>> 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

Another one using for but kind of a hack

>>> 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


I don't think you can (or should) do this with a regular for list-iterator. You may want to look at this as a case of a work queue and use a while loop:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消