[Tutor] Finding items in list of lists.

Gregor Lingl glingl@aon.at
Tue Mar 18 02:17:02 2003


Doug.Shawhan@gecits.ge.com schrieb:

>I am confusing myself.
>
>I have a list that contains the following:
>
>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?
>
Hi  Doug!
You could mix it with something "less friendly" (???) and first
flatten your list of lists l by using reduce:

from operator import add
 >>> reduce(add,l)
['joe', 'moe', 'schmoe', 'fee', 'foo', 'bar']

With this a single comprehension would do it:

 >>> [y for y in reduce(add,l) if y in ("moe", "foo")]
['moe', 'foo']
 >>>

Regards, Gregor

>
>d
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>