Darren Haynes
Darren Haynes

Reputation: 1353

Convert For Loop to List Comprehension: Testing if elements in list 2 are partial match for elements in list 1

somewhat of a python/programming newbie here,

I have come up with a code of 2 nested for loops to test if the elements of the the 2nd loop are a partial (or complete) match of the elements in the first list, and if so those elements are removed from the 1st list. Here is the code:

>>> lst = ["my name is Bob Jenkins", "Tommy Cooper I am", "I be Bazil", "I Tarzan"]
>>> names = ["Bob", "Tarzan"]
>>> for l in lst:
        for n in names:
            if n in l:
                lst.remove(l)


>>> print lst
['Tommy Cooper I am', 'I be Bazil']

The problem here is that I don't actual want to modify lst, but create a new list. Thus list comprehension raises its head. However, I have not been able to figure out a list comprehension to pull this off. I have tried [i for i in lst for n in names if n not in i] but this does not work. Of course the .remove method is not for list comprehension. I have been puzzling for the past hour, but cannot come up with anything.

Any ideas?

Upvotes: 0

Views: 413

Answers (3)

roippi
roippi

Reputation: 25974

For completeness, filter:

filter(lambda s: not any(x in s for x in names),lst)
Out[4]: ['Tommy Cooper I am', 'I be Bazil']

For python 3, list(filter):

list(filter(lambda s: not any(x in s for x in names),lst))
Out[4]: ['Tommy Cooper I am', 'I be Bazil']

Upvotes: 1

Peter DeGlopper
Peter DeGlopper

Reputation: 37364

I'd use the any built in function:

newlst = [i for i in lst if not any(name in i for name in names)]

If you prefer, this expression using all is equivalent:

newlst = [i for i in lst if all(name not in i for name in names)]

Upvotes: 1

darkryder
darkryder

Reputation: 832

There you go :) :

lst = ["my name is Bob Jenkins", "Tommy Cooper I am", "I be Bazil", "I Tarzan"]
names = ["Bob", "Tarzan"]

new=[a for a in lst if all(x not in a for x in names) ]
print new

Upvotes: 1

Related Questions