2010-02-02 68 views
24

如何在Python中儘早留下循環?Python早退循環

for a in b: 
    if criteria in list1: 
     print "oh no" 
     #Force loop i.e. force next iteration without going on 
    someList.append(a) 

此外,在Java中,你可以break退出循環,有沒有在Python等效?

+5

不要使用'list'作爲變量名稱。它隱藏了內建。 – 2010-02-02 13:34:02

回答

42

continuebreak是你想要的。 Python在這方面的工作原理與Java/C++相同。

+2

好奇隨意;你是來自Bethesda論壇的「Max_aka_NOBODY」嗎?你分享相同的化身,這就是爲什麼我想知道。 – Yacoby 2010-02-02 13:30:54

+2

的確我是。 :d – 2010-02-02 13:32:48

15

首先,請記住它可能會做你想要的清單理解。所以,你可能能夠使用這樣的:如果你想退出循環在Python早期可以使用break

somelist = [a for a in b if not a.criteria in otherlist] 

,就像在Java中。

>>> for x in xrange(1,6): 
...  print x 
...  if x == 2: 
...   break 
... 
1 
2 

如果你想開始循環的下一次迭代的早期使用continue,再次就像你在Java中那樣。

>>> for x in xrange(1,6): 
...  if x == 2: 
...   continue 
...  print x 
... 
1 
3 
4 
5 

Here's the documentation for break and continue.這也包括else條款for循環,這是不運行時,你break

4

continuebreak的工作方式與其他編程語言完全相同,只是不能將break添加到標籤(例如,您可以在Java中)。這意味着您一次只能打破一個循環。