Python在转到else statemen之前检查整个循环

2024-05-06 15:59:43 发布

您现在位置:Python中文网/ 问答频道 /正文

如果if条件为false,如何遍历整个循环,然后在go to else语句之后运行?你知道吗

输出为:

No

No

Yes

但我只希望它跳到else语句,如果所有的值都不相等!你知道吗

test_1 = (255, 200, 100)
test_2 = (200, 200, 100)
test_3 = (500, 50, 200)

dict = {"test_1":test_1,
        "test_2":test_2,
        "test_3":test_3}


for item in dict:
   if dict[item] == (500, 50, 200):
        print('Yes')
   else:
        print('No')

所以基本上输出应该是这样的,因为其中一个值是真的。你知道吗

Yes


Tags: tonointestfalsegoforif
3条回答

可以使用in运算符:

item_appears_in_dict = item in dict.values()
print "Yes" if item_appears_in_dict else "No"

你需要运行循环直到找到匹配的。为此,可以使用^{}函数,如下所示

if any(dict_object[key] == (500, 50, 200) for key in dict_object):
    print('Yes')
else:
    print('No')

我们将生成器表达式传递给any函数。生成器表达式从dict中获取每个项并检查它是否等于(500, 50, 200)。一旦找到匹配项,any将立即返回True,其余的迭代甚至不会进行。如果没有与(500, 50, 200)匹配的项,any将返回FalseNo将被打印。你知道吗


编辑:在聊天中与OP进行了长时间的讨论之后,他实际上想知道哪个项目也匹配。所以,更好的解决方案是使用for..else,就像NPE的另一个答案,像这样

for key in dict_object:
   if key.startswith('test_') and dict_object[key] == (500, 50, 200):
        # Make use of `dict_object[key]` and `key` here
        break
else:
    print('No matches')

But I only want it to jump to the else statement if all of the values does not equal!

Python的for-else构造可以用来实现这一点:

for item in dict:
   if dict[item] == (500, 50, 200):
        print('Yes')
        break
else:
    print('No')

有关进一步讨论,请参见Why does python use 'else' after for and while loops?

但是,在这个特定的实例中,我根本不会使用显式循环:

print ("Yes" if (500, 50, 200) in dict.values() else "No")

相关问题 更多 >