简体   繁体   English

如何在python的循环中移至循环的下一个迭代?

[英]How to move onto the next iteration of a loop within a loop in python?

Take for example the code below with 2 for loops. 例如,下面的代码带有2个for循环。

for xy in set:
        for name in dict:
            if xy == name:
               print("Yay")

What I'm wondering is, if after the if statement is found to be true, will it keep iterating through 'dict' or will it go back upto the first for loop and move onto the next iteration? 我想知道的是,如果在发现if语句为真之后,它将继续通过“ dict”进行迭代,还是返回到第一个for循环并移至下一个迭代? I can't believe how long I've been using python and I don't know the answer to such a simple question. 我不敢相信我使用python已经有多长时间了,我也不知道这个简单问题的答案。

Thanks! 谢谢!

It will continue to iterate in dict. 它将继续迭代dict。 If you want to jump out of the inner loop, use break . 如果要跳出内循环,请使用break

You can also try. 您也可以尝试。

if any(name in dict for name in set):
    print('Yay')

It keep iterate through dict . 它通过dict保持迭代。

If you want the loop go back upto first for loop, use break statement : 如果你想在环回高达第一个for循环,使用break声明

for xy in set:
    for name in dict:
        if xy == name:
           print("Yay")
           break

As Jacob Krall commented, You don't need to iterate the dictionary object to check whether key( name ) exist. 正如Jacob Krall所评论的那样,您不需要迭代字典对象来检查key( name )是否存在。 Use in operator: in运算符中使用:

>>> d = {'sam': 'Samuel', 'bob': 'Robert'}
>>> 'bob' in d
True
>>> 'tom' in d
False

for xy in set:
    if name in dict:
        print("Yay")

If you want print Yay only once, use set.isdisjoint : 如果只打印一次Yay ,请使用set.isdisjoint

if not set.isdisjoint(dict):
    print("Yay")

BTW, do not use set or dict as variable name. 顺便说一句,不要使用setdict作为变量名。 It shadows builtin function set , dict . 它内建阴影的功能setdict

It will continue to iterate over dict . 它将继续对dict进行迭代。 If you do not want this behavior try this: 如果您不希望出现这种情况,请尝试以下操作:

for xy in set:
    for name in dict:
        if xy == name:
           print("Yay")
           break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM