'Advanced' list comprehension? query
tenax.raccoon at gmail.com
Wed Aug 8 18:47:52 CEST 2007
On Aug 8, 10:00 am, pyscottish... at hotmail.com wrote:
> I'm playing around with list comprehension, and I'm trying to find the
> most aesthetic way to do the following:
> I have two lists:
> noShowList = ['one', 'two', 'three']
> myList = ['item one', 'item four', 'three item']
> I want to show all the items from 'myList' that do not contain any of
> the strings in 'noShowList'.
> i.e. 'item four'
> I can do it like this:
> def inItem(noShowList, listitem):
> return [x for x in noShowList if x in listitem]
> print [x for x in myList if not inItem(noShowList, x)]
> and I can do it (horribly) with:
> print [x for x in myList if not (lambda y, z:[i for i in y if i in z])
> (noShowList, x)]
> I can also print out the items that DO contain the 'noShowList'
> strings with:
> print [x for x in myList for y in noShowList if y in x]
> but I can't get the 'not' bit to work in the above line.
> Any ideas?
Here's how I would do it:
['one', 'two', 'four']
['item one', 'item two', 'item three', 'item four', 'item five']
>>> [x for x in myList if not any(y in x for y in noShowList)]
['item three', 'item five']
More information about the Python-list