1

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

3 Answers 3

7

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')
Sign up to request clarification or add additional context in comments.

3 Comments

imo this is the best way
How do we do the opposite, example, if item[1] != 'ABC' and any(keyword in item[2] for keyword in keywords): to get tuple 3 and 4?
@jxn well, this would give you the tuple 3: if item[1] != 'ABC' and all(keyword not in item[2] for keyword in keywords):. Basically, we are asking for all keywords not to match.
3

You don't, because in with a sequence only matches the whole element.

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.