Rewriting Recipe/410687 without map and lambda

Terry Reedy tjreedy at udel.edu
Tue Dec 11 23:29:07 EST 2007


"sofeng" <sofengboe at gmail.com> wrote in message 
news:ea3c295f-fc27-40a1-a903-7504dd45ea6f at s19g2000prg.googlegroups.com...
|I would like to use the following recipe to transpose a list of lists
| with different lengths. 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410687
|
| Here is an example of what I would like to do:
|
| Python 2.5.1 (r251:54863, May 18 2007, 16:56:43)
| [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
| Type "help", "copyright", "credits" or "license" for more information.
| >>> a = [[1,2,3],[4,5,6,7],[8,9]]
| >>> print map(lambda *row: list(row), *a)
| [[1, 4, 8], [2, 5, 9], [3, 6, None], [None, 7, None]]
| >>>
|
| However, in the Python 3000 FAQ (http://www.artima.com/weblogs/
| viewpost.jsp?thread=211200), Guido says not to use map with lambda
| because a list comprehension is clearer and faster.
|
| How can I rewrite the above recipe using a list comprehension instead?

Here is the sort of thing Guido is talking about:

>>> a = [[1,2,3],[4,5,6,7],[8,9]]
>>> [list(r) for r in zip(*a)]
[[1, 4, 8], [2, 5, 9]]

Except in this case, zip does not pad, while map does, so the list comp 
form has to be

>>> [list(r) for r in map(None, *a)]
[[1, 4, 8], [2, 5, 9], [3, 6, None], [None, 7, None]]

but at this point, it is about as easy to put the lambda in place of None.

But when one maps one sequence or equal-length sequences, Guido's point 
applies.

tjr






More information about the Python-list mailing list