'Advanced' list comprehension? query

danmcleran at yahoo.com danmcleran at yahoo.com
Wed Aug 8 12:37:47 EDT 2007


On Aug 8, 10:00 am, pyscottish... at hotmail.com wrote:
> Hi,
>
> 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?
> Thanks!

import itertools

from itertools import ifilter

noShowList = ['one', 'two', 'three']
myList = ['item one', 'item four', 'three item']

result = list(ifilter(lambda x: True not in [item in x for item in
noShowList], myList))

print result

>>>['item four']




More information about the Python-list mailing list