问题
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?
回答1:
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
回答2:
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)]
回答3:
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']
来源:https://stackoverflow.com/questions/21653585/convert-for-loop-to-list-comprehension-testing-if-elements-in-list-2-are-partia