how to flatten one level of list of lists?
Alex Martelli
aleaxit at yahoo.com
Tue May 29 15:17:24 EDT 2001
"George Young" <gry at ll.mit.edu> wrote in message
news:3B13DE0C.76270DAA at ll.mit.edu...
> I have a list like:
> l = [[2], [3], [5], [11]]
> and I want to get:
> ll = [2, 3, 5, 11]
>
> I know I can do something like:
> ll = map(lambda i: i[0],l)
>
> but it seems like overkill to have to use a lamba for such a simple
> task. Is there some easy way I'm missing?
List comprehension:
ll = [x for y in l for x in y]
or
ll = [x[0] for x in l]
> BTW, I tried to use l.__getitem__ or l.__getslice__ with map, but both
> failed with AttributeError. (this is python 2.1) The 2.1 docs seem to
> say these members exist for lists -- what's wrong?
Maybe ambiguous docs? If you can pinpoint the erroneous parts,
they can no doubt be fixed...
You can use map if you wish, and without lambdas, but:
import operator
ll = map(operator.getitem, l, [0]*len(l))
...that's not very slick here imho, since you have to replicate the [0].
But even if you could bind l.getitem, how would it help you here?
Alex
More information about the Python-list
mailing list