Jaja
Jaja

Reputation: 55

Check if not in list - more conditions in Python

I have two lists with not fixed number of items, e. g.:

data=['sun','stars','moon','supermoon','planet','comet','galaxy']

forbidden=['mo','st','lax']

I need to print only those items of data which do not contain any of the strings listed in forbidden. In this case the output would be

sun
planet
comet

What I tried is

print [x for x in data if forbidden not in x ]

which works only for one condition (one item in forbidden list)

Is there any way how to check all the conditions at once?

In case I knew the number of items in forbidden I could use

print [x for x in data if forbidden[0] not in x and forbidden[1] not in x]

but it does not work with unknown number of items.

Thank you for help.

Upvotes: 4

Views: 245

Answers (2)

gold_cy
gold_cy

Reputation: 14216

Here is more of a functional approach:

from itertools import product
from operator import contains, itemgetter

first = itemgetter(0)

p = product(data, forbidden)
f = filter(lambda tup: contains(*tup), p)
set(data).difference(set(map(first, f)))

{'comet', 'planet', 'sun'}  # order is not preserved here if that matters

Edit: If the data is large this will handle it more gracefully and return results faster

Upvotes: 2

Ajax1234
Ajax1234

Reputation: 71451

You can use all:

data=['sun','stars','moon','supermoon','planet','comet','galaxy']
forbidden=['mo','st','lax']
print([i for i in data if all(c not in i for c in forbidden)])

Output:

['sun', 'planet', 'comet']

Upvotes: 5

Related Questions