Aleksnadra
Aleksnadra

Reputation: 11

PYTHON: Multiple conditions in list comprehensions - matching strings

I have:

mylist = ['person1 has apples', 'oranges and apples', 'person2 has oranges']

matchers = ['person1','person2']

My desire output is a list of strings that contain strings in matchers:

output = ['person1 has apples', 'person2 has oranges']

I have managed to achieve this writing out each item from matching list explicitly, but the actual data is much bigger than this example so I am looking for better way to achieve the output.

This works:

matching = [s for s in mylist if "person1" in s or "person2" in s]

But it requires listing every item from matchers explicitly.

I have tried this:

matching = [s for s in mylist if any(x in s for x in matchers)]

But I'm getting the following error message:

'in <string>' requires string as left operand, not float

However, it only produces an error message when there are no matches in the list of strings. When there is a match from matchers in mylist - the code works. Not sure why!

** EDIT - typo corrected. There was no typo in the code that produced the error **

** EDIT2 - code is correct, there was a NaN in the list of matchers! **

Upvotes: 1

Views: 1115

Answers (2)

AKX
AKX

Reputation: 169032

You have a typo; you've probably assigned a float to x earlier, and

matching = [s for s in mylist if any(x in s for xs in matchers)]

refers to it.

Maybe be more explicit with names:

matching = [text for text in mylist if any((matcher in text) for matcher in matchers)]

An example

mylist = [
    "person1 has apples",
    "oranges and apples",
    "person2 has oranges",
]
matchers = ["person1", "person2"]
matching = [
    text
    for text in mylist
    if any(matcher in text for matcher in matchers)
]
print(mylist)
print(matchers)
print(matching)

outputs

['person1 has apples', 'oranges and apples', 'person2 has oranges']
['person1', 'person2']
['person1 has apples', 'person2 has oranges']

Upvotes: 1

JoKing
JoKing

Reputation: 470

How about this: matching = [s for s in mylist if any(m in s for m in matchers)]

Upvotes: 0

Related Questions