简体   繁体   中英

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.

    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:

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. 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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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