Ningxi
Ningxi

Reputation: 157

Python remove element in list

I have a question

say I have two list, and each of them contains couple of strings

a = ['x', 'y', 'z', 't'] b = ['xyz', 'yzx', 'xyw']

I want to delete xyw in list b, because w is not in list a.

I tried

for s in a:
    k = [t for t in b if t.find(s)]

but it didn't work Does anyone know how to do this in Python? Thank you!

Upvotes: 1

Views: 177

Answers (2)

BigTailWolf
BigTailWolf

Reputation: 1028

>>> a = ['x', 'y', 'z']
>>> b = ['xyz', 'yzx', 'xyw']
>>> for element in b:
...     if not all(i in a for i in element):
...         b.remove(element)
... 
>>> b
['xyz', 'yzx']
>>> 

Correcttion: I shouldn't delete during iterating. So following like the solution above fits

>>> a = ['x', 'y', 'z']
>>> b = ['xyz', 'yzx', 'xyw']
>>> b = [i for i in b if all(j in a for j in i)]
>>> b
['xyz', 'yzx']
>>>

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117856

You could check that all of the letters in each string are contained in your list a then filter out strings using a list comprehension.

>>> a = ['x', 'y', 'z']
>>> b = ['xyz', 'yzx', 'xyw']
>>> [i for i in b if all(j in a for j in i)]
['xyz', 'yzx']

Upvotes: 3

Related Questions