0

Example:

a = ['abc123','abc','543234','blah','tete','head','loo2']

So I want to filter out from the above array of strings the following array b = ['ab','2']

I want to remove strings containing 'ab' from that list along with other strings in the array so that I get the following:

a = ['blah', 'tete', 'head']

3 Answers 3

5

You can use a list comprehension:

[i for i in a if not any(x in i for x in b)]

This returns:

['blah', 'tete', 'head']
Sign up to request clarification or add additional context in comments.

6 Comments

It gives the original 'a' values
@LP What do you mean?
@Haidro your first iteration was wrong. +1 But the readability of this one is horrible :)
@limelights I'm on my phone :p
@LP Yea, sorry about that. I must have just fixed that after you commented. Anyways, glad I helped :)
|
2
>>> a = ['abc123','abc','543234','blah','tete','head','loo2']
>>> b = ['ab','2']
>>> [e for e in a if not [s for s in b if s in e]]
['blah', 'tete', 'head']

Comments

1
newA = []
for c in a:
    for d in b:
        if d not in c:
            newA.append(c)
            break
a = newA

2 Comments

Although this is correct, it is a much slower solution (albeit more readable:)). Just a tip, you can use break after the if ... as you don't need to search anymore (this is what any does, btw).
Actually you are right and it is necessary to avoid adding twice.

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.