[Tutor] Finding items in list of lists.

Doug.Shawhan@gecits.ge.com Doug.Shawhan@gecits.ge.com
Mon Mar 17 13:23:02 2003


>> l = [["joe", "moe", "schmoe"], ["fee", "foo", "bar"]]

>> I wish to check for the existence of both "moe" and "foo" in l. Is there
a
>> clear way to do so using list comprehension, or must I result to
something
>> less friendly?

> A nested list needs nested comprehension:

> [[y for y in x if y in ("moe", "foo")] for x in l]

> will return [['moe'], ['foo']].

This is really cool and helps me to understand list comprehension somewhat
better, but it does not actually do what I need (sorry, I am dense!).

Perhaps list comprehension muddied the trail, since I _expected_ it to be
able to solve the problem. What I need to do is check for the existence of
two items in the list of lists so I can filter them out.

Say I have a set of critera that can be matched: (fat, skinny), (hairy,
bald), (ugly, svelte), (smelly, sweet).

These criteria are spread through several lists that are contained in other
lists:

I need to match the criteria like so:

-------------------------
in: [['joe', 'fat', 'light', 'dark'], ['joe','hairy','nekkid','ugly'],
['joe', 'skinny', 'ugly', 'sweet'], ['joe','bald','silly','wacky]]

out:	[['joe', 'fat', 'light', 'dark'],['joe', 'skinny', 'ugly', 'sweet']]
	[['joe','hairy','nekkid','ugly'], ['joe','bald','silly','wacky]]
-------------------------

.. and would like to avoid a mass of if loops. Or do I just need to suck it
up? :-)