如何在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等效?
如何在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等效?
continue
和break
是你想要的。 Python在这方面的工作原理与Java/C++相同。
好奇随意;你是来自Bethesda论坛的“Max_aka_NOBODY”吗?你分享相同的化身,这就是为什么我想知道。 – Yacoby 2010-02-02 13:30:54
的确我是。 :d – 2010-02-02 13:32:48
看看break
和continue
。
首先,请记住它可能会做你想要的清单理解。所以,你可能能够使用这样的:如果你想退出循环在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
。
continue
和break
的工作方式与其他编程语言完全相同,只是不能将break
添加到标签(例如,您可以在Java中)。这意味着您一次只能打破一个循环。
不要使用'list'作为变量名称。它隐藏了内建。 – 2010-02-02 13:34:02