Iterate again within the for loop

前端 未结 7 1019
走了就别回头了
走了就别回头了 2021-01-21 07:50

is there a way to iterate again within the for loop? For example:

for x in list:
  if(condition):
      #I\'d like to grab the next iteration of the lis         


        
7条回答
  •  旧时难觅i
    2021-01-21 08:43

    If the item you're using over is an iterable object you can use item.next() to grab the next element. But you'll need to make sure to grab the StopIteration exception if needed.

    >>> it = iter(range(5))
    >>> for x in it:
    ...     print x
    ...     if x > 3:
    ...         print it.next()
    ... 
    0 1 2 3 4
    Traceback (most recent call last):
      File "", line 4, in 
    StopIteration
    

提交回复
热议问题