简体   繁体   English

For 循环在 If 语句中 Python

[英]For Loop Within an If Statement Python

I am using a for-loop within another for-loop to iterate through and compare two data sets.我在另一个 for 循环中使用一个 for 循环来迭代和比较两个数据集。 I want to first use the inner for loop to check for a condition and then, if it fails, to print a value from the outer loop.我想首先使用内部 for 循环来检查条件,然后,如果失败,则从外部循环打印一个值。

For example:例如:

for (i) in list_one:

    for (j) in list_two:
        
        if (condition):

            print(j)

if the condition for 'print(j)' fails for all instances in list_two, I want the current value of list_one to be printed.如果 list_two 中所有实例的“print(j)”条件均失败,我希望打印 list_one 的当前值。 Something like an 'if: for:' statement seems like it would make sense but I'm not sure if those are possible in Python. Thanks for the help像“if:for:”这样的语句似乎是有道理的,但我不确定在 Python 中是否可行。谢谢你的帮助

You can just add a fail flag, like你可以只添加一个失败标志,比如

for (i) in list_one:
    fail = True
    for (j) in list_two:
        if (condition):
            fail = False
            print(j)
    if fail:
        print(i)

If you need to print only the first satisfy condition and then break out of the loop, then you can use for... else如果只需要打印第一个满足condition然后跳出循环,那么可以使用for... else

for (i) in list_one:
    for (j) in list_two:
        if (condition):
            print(j)
            break
    else:
        print(i)

If you want to print all the values which satisfy the condition in inner loop, you can use one more variable如果你想在内部循环中打印所有满足condition的值,你可以使用一个变量

for (i) in list_one:
    print_i = True
    for (j) in list_two:
        if (condition):
            print(j)
            print_i = False
    if print_i:
        print(i)

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

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