do you master list comprehensions?
jstroud at mbi.ucla.edu
Tue Dec 14 03:13:16 CET 2004
Here is one for arbitrary depth:
unrolled = 
for item in ary:
# add test for your favorite sequence type
if ( type(item) == types.ListType or \
type(item) == types.TupleType \
>>> unroll([[1, 2, 3], ('fred', 'barney', ['wilma', 'betty']), 'dino'])
[1, 2, 3, 'fred', 'barney', 'wilma', 'betty', 'dino']
On Monday 13 December 2004 12:51 pm, Will Stuyvesant wrote:
> Here is a question about list comprehensions [lc]. The
> question is dumb because I can do without [lc]; but I am
> posing the question because I am curious.
> >>> data = [['foo','bar','baz'],['my','your'],['holy','grail']]
> >>> result = 
> >>> for d in data:
> ... for w in d:
> ... result.append(w)
> >>> print result
> ['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail']
> puts all the words in a list, like I want.
> How to do this with [lc] instead of for-loops?
> I tried funnies like [[w for w in L] for L in data],
> that is correct syntax, but you'd never guess.
> I know, silly! No need for [lc]! So there's my
> question. I am sure a one-liner using [lc] will be very
> enlightening. Like studying LISP.
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
611 Charles E. Young Dr. S.
MBI 205, UCLA 951570
Los Angeles CA 90095-1570
More information about the Python-list