집 > Q&A > 본문
1
2
3
4
5
6
7
8
9
10
11
isbreak=False
isbreak
=
False
for i in ['a','b','c']:
for
i
in
[
'a'
,
'b'
'c'
]:
for ii in range(5):
ii
range
(
):
print i,ii
print
i,ii
if ii==2:
if
:
print 'ii=2时,内层循环break,同时外层循环break'
'ii=2时,内层循环break,同时外层循环break'
isbreak=True
True
break
if isbreak:
isbreak:
除了以上写法,还有什么好的写法呢?多谢您的回复!
三叔2016-10-22 16:45:44
你這個例子似乎可以考慮減少循環即可:
import itertools
import
itertools
lst = ['a', 'b', 'c']
lst
]
for i, ii in itertools.product(lst, range(5)):
i, ii
itertools.product(lst,
)):
print i, ii
真要說這種一次跳出多層 loop 的辦法有一個, 利用 exception:
class Found(Exception): pass
class
Found(Exception):
pass
try:
try
for lst2 in lst1:
lst2
lst1:
for lst3 in lst2:
lst3
lst2:
for item in lst3:
item
lst3:
if item=='good':
'good'
raise Found
raise
Found
except Found:
except
Found:
我回答過的問題: Python-QA