Asteroid098
Asteroid098

Reputation: 2825

use list comprehensions to eliminate strings in list that include substrings in another list

I have two lists:

list_1 = ['https:/zh-cn.fb.com/siml15', 'https:/fb.com/siml29','https:/en-gb.fb.com/siml29','https:/fb.com/siml4529','https:/pt-br.fb.com/siml29']
list_2 = ['zh-cn','en-gb','es-la','fr-fr','ar-ar','pt-br','ko-kr','it-it','de-de','hi-in','ja-jp']

I need to remove items in list_1 that includes substrings in list_2

The wanted output:

['https:/fb.com/siml29','https:/fb.com/siml4529']

Is there a way to use list comprehensions twice?

[x for x in list_1 if y for y in list_2 not in x]

Upvotes: 0

Views: 13

Answers (1)

ywbaek
ywbaek

Reputation: 3031

You can use inner comprehension and all function for this:

list_1 = ['https:/zh-cn.fb.com/siml15', 'https:/fb.com/siml29', 'https:/en-gb.fb.com/siml29', 'https:/fb.com/siml4529', 'https:/pt-br.fb.com/siml29']
list_2 = ['zh-cn', 'en-gb', 'es-la', 'fr-fr', 'ar-ar', 'pt-br', 'ko-kr', 'it-it', 'de-de', 'hi-in', 'ja-jp']

result = [x for x in list_1 if all(y not in x for y in list_2)]

print(result)
['https:/fb.com/siml29', 'https:/fb.com/siml4529']

Upvotes: 1

Related Questions