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

jxn*_*jxn 1 python loops operators

我有一个元组列表,我在一个简单的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')]
Run Code Online (Sandbox Code Playgroud)

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

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

上面的代码不起作用,没有打印任何内容.

下面的代码有效,但非常罗嗦.我怎么做它像上面那样?

for tup in mytuplist:
    if tup[1] =='ABC' and 'Today is' in tup[2] or 'The sky' in tup[2]:
        print tup
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 7

你应该使用内置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)
Run Code Online (Sandbox Code Playgroud)

打印:

(1, 'ABC', 'Today is a great day')
(2, 'ABC', 'The sky is blue')
Run Code Online (Sandbox Code Playgroud)

  • imo这是最好的方式 (2认同)