sudonym
sudonym

Reputation: 4018

How to include boolean conditions to python's list comprehension?

INPUT: I have a list of strings with places I can work:

ALL_CHANCES = ['I can work in China',
               'I can work in Germany',
               'I can work in Singapore',
               'I can work in Norway']

I have another list of strings with places better not to work at:

HIGH_TAX = ['Germany',
            'Norway']

OUTPUT: I am looking for a simple list comprehension one-liner to filter list 1 for items that have substrings occurring in list 2:

GOOD_CHANCES = ['I can work in China',
                'I can work in Singapore']

CHALLENGE:

However, when I do

GOOD_CHANCES  = [item for item in ALL_CHANCES
                      if (not any(word for word in HIGH_TAX) in item)]

I yield the following error:

'<string>' requires string as left operand, not bool 

How to include boolean conditions to python's list comprehension?

Upvotes: 2

Views: 827

Answers (2)

ssm
ssm

Reputation: 5373

The simplest way of doing this is:

[item for item in ALL_CHANCES if item.split()[-1] not in HIGH_TAX]

This is assuming that all the countries are at the end of the sentence.

It the country may be present anywhere, you might try:

[item for item in ALL_CHANCES if not any( h in item for h in HIGH_TAX )  ]

Upvotes: 1

sshashank124
sshashank124

Reputation: 32189

You can do it simpler as follows:

GOOD_CHANCES  = [item for item in ALL_CHANCES \
                  if not any(word in item for word in HIGH_TAX)]

In your solution, not any(word for word in HIGH_TAX) is evaluating to a bool which is then being compared to the string item. Instead as shown above, you can include the substring check in the any method call itself

It might also be clearer to use the filter method:

filter(lambda item: not any(word in item for word in HIGH_TAX), ALL_CHANCES)

Upvotes: 1

Related Questions