简体   繁体   English

Python在“ IF ELSE”循环中使用“ IN”

[英]Python using “IN” in a “IF ELSE” loop

i have a list of tuples that i loop through in a simple for loop to identify tuples that contain some conditions. 我有一个元组列表,我在一个简单的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')]

I want it to be efficient and readable like this: 我希望它像这样高效且易读:

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

The above code does not work and nothing gets printed. 上面的代码不起作用,什么也没打印。

This code below works but is very wordy. 下面的代码可以工作,但是非常麻烦。 How do i make it like the above? 我如何像上面那样?

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

You should use the built-in any() function: 您应该使用内置的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)

Prints: 印刷品:

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

您不需要,因为in与序列仅匹配整个元素。

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

Your second approach (which, however, needs to be parenthesized as x and (y or z) to be correct) is necessary tup[2] contains one of your key phrases, rather than being an element of your set of key phrases. 您的第二种方法(不过,必须将其用x and (y or z)括起来才能正确)括起来) tup[2] 包含您的一个关键短语,而不是您的一组关键短语中的一个。 You could use regular-expression matching at the cost of some performance: 您可以使用正则表达式匹配,但会降低性能:

if tup[1] == 'ABC' and re.match('Today is|The sky', tup[2])

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

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