正如你在我的if语句中所看到的,我有多个条件,我怎样才能将它缩短为一个?
我希望它是这样的例子:
if (['5', 'Blue'] and ['10', 'Blue'] and ['60', 'Blue']) in clicked_items:
print("2, 2a, 3, 4, 5, 5a components are dry.")
我目前的代码:
if ['5', 'Blue'] in clicked_items and ['10', 'Blue'] in clicked_items and ['60', 'Blue'] in clicked_items:
print("2, 2a, 3, 4, 5, 5a components are dry.")
答案 0 :(得分:3)
此行符合您的要求:
if all([n, 'Blue'] in clicked_items for n in ('5', '10', '60')):
以下是完整程序中使用的上述行。它在第一个条件下打印“干”,在第二个条件下打印“nope”。
clicked_items = (
['1', 'Red'],
['5', 'Blue'],
['10', 'Blue'],
['60', 'Blue'],
['70', 'Blue'],
)
if all([n, 'Blue'] in clicked_items for n in ('5', '10', '60')):
print("2, 2a, 3, 4, 5, 5a components are dry.")
else:
print("Nope")
clicked_items = (
['1', 'Red'],
['5', 'Blue'],
['10', 'Red'],
['60', 'Blue'],
['70', 'Blue'],
)
if all([n, 'Blue'] in clicked_items for n in ('5', '10', '60')):
print("2, 2a, 3, 4, 5, 5a components are dry.")
else:
print("Nope")
如果并非所有颜色都是蓝色,那么生成器表达式可能需要不同,如下所示:
if all([n, color] in clicked_items
for n, color in [['60', 'Pink'], ['10', 'Blue'], ['5', 'Red']]):