[英]How to move onto the next iteration of a loop within a loop in python?
例如,下面的代碼帶有2個for循環。
for xy in set:
for name in dict:
if xy == name:
print("Yay")
我想知道的是,如果在發現if語句為真之后,它將繼續通過“ dict”進行迭代,還是返回到第一個for循環並移至下一個迭代? 我不敢相信我使用python已經有多長時間了,我也不知道這個簡單問題的答案。
謝謝!
它將繼續迭代dict。 如果要跳出內循環,請使用break
。
您也可以嘗試。
if any(name in dict for name in set):
print('Yay')
它通過dict
保持迭代。
如果你想在環回高達第一個for
循環,使用break
聲明 :
for xy in set:
for name in dict:
if xy == name:
print("Yay")
break
正如Jacob Krall所評論的那樣,您不需要迭代字典對象來檢查key( name
)是否存在。 in
運算符中使用:
>>> d = {'sam': 'Samuel', 'bob': 'Robert'}
>>> 'bob' in d
True
>>> 'tom' in d
False
for xy in set:
if name in dict:
print("Yay")
如果只打印一次Yay
,請使用set.isdisjoint
:
if not set.isdisjoint(dict):
print("Yay")
它將繼續對dict
進行迭代。 如果您不希望出現這種情況,請嘗試以下操作:
for xy in set:
for name in dict:
if xy == name:
print("Yay")
break
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.