Skip to main content
 首页 » 编程设计

Python 在 "IN"循环中使用 "IF ELSE"

2025年05月04日10xiaohuochai

我有一个元组列表,我在一个简单的 for 循环中循环遍历这些元组,以识别包含某些条件的元组。

    mytuplist =  
    [(1, 'ABC', 'Today is a great day'), (2, 'ABC', 'The sky is blue'),  
     (3, 'DEF', 'The sea is green'), (4, 'ABC', 'There are clouds in the sky')] 

我希望它像这样高效且可读:

    for tup in mytuplist: 
        if tup[1] =='ABC' and tup[2] in ('Today is','The sky'): 
            print tup 

上面的代码不起作用,也没有打印任何东西。

下面的代码有效,但非常冗长。我如何使它像上面那样?

for tup in mytuplist: 
    if tup[1] =='ABC' and 'Today is' in tup[2] or 'The sky' in tup[2]: 
        print tup 

请您参考如下方法:

您应该使用内置的 any()功能:

mytuplist = [ 
    (1, 'ABC', 'Today is a great day'), 
    (2, 'ABC', 'The sky is blue'), 
    (3, 'DEF', 'The sea is green'), 
    (4, 'ABC', 'There are clouds in the sky') 
] 
 
keywords = ['Today is', 'The sky'] 
for item in mytuplist: 
    if item[1] == 'ABC' and any(keyword in item[2] for keyword in keywords): 
        print(item) 

打印:

(1, 'ABC', 'Today is a great day') 
(2, 'ABC', 'The sky is blue')