Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 715
Jaja Avatar asked Mar 04 '23 14:03

Jaja


1 Answers

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']
like image 75
Ajax1234 Avatar answered Mar 15 '23 05:03

Ajax1234