1

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!

Ningxi
  • 157
  • 2
  • 9
  • 2
    I'm sorry but as SO is not a *do it for me* site you need to show us that what you have tried so far! then we can help you on your problems! – Mazdak Feb 17 '15 at 16:22
  • @KasraAD thanks for your reminder, I just join this website. I did have a try, I changed my question. – Ningxi Feb 17 '15 at 16:35
  • welcome! OK, always remember that as you explain more about your question as you get a complete answer! – Mazdak Feb 17 '15 at 16:37

2 Answers2

3

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']
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Great! But if a = ['x', 'y', 'z', 't'], how to change the code? thanks! – Ningxi Feb 17 '15 at 16:24
  • I tried , but the answer is [] ... I also tried [i for i in b if any(j in i for j in a)], the answer is ['xyz', 'yzx', 'xyw'] ... – Ningxi Feb 17 '15 at 16:28
1
>>> 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']
>>>
BigTailWolf
  • 1,028
  • 6
  • 17
  • This fails for e.g. `b = ['xyz', 'yzx', 'xyw', 'xyq']`, because you're removing items from the list as you iterate over it. – Zero Piraeus Feb 17 '15 at 17:03
  • @ZeroPiraeus Oh, I got. I shouldn't do that. I should follow the above solution and reassign to b. Is that correct? – BigTailWolf Feb 17 '15 at 19:40