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!

3
  • 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! Commented Feb 17, 2015 at 16:22
  • @KasraAD thanks for your reminder, I just join this website. I did have a try, I changed my question. Commented Feb 17, 2015 at 16:35
  • welcome! OK, always remember that as you explain more about your question as you get a complete answer! Commented Feb 17, 2015 at 16:37

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

2 Comments

Great! But if a = ['x', 'y', 'z', 't'], how to change the code? thanks!
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'] ...
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']
>>>

2 Comments

This fails for e.g. b = ['xyz', 'yzx', 'xyw', 'xyq'], because you're removing items from the list as you iterate over it.
@ZeroPiraeus Oh, I got. I shouldn't do that. I should follow the above solution and reassign to b. Is that correct?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.