Muffinresearch Labs by Stuart Colville

Python: Transposing Lists With map and zip | Comments (2)

Posted in Code on 16th October 2007, 11:05 am by Stuart

I’m re-writing a piece of code to print into columns within a terminal and I wanted to join the nth items of each list together. Zip allows you to do just that

>>> list=[[1,2,3],[4,5,6],[7,8,9,10]]
>>> print zip(*list)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

But truncates the output to the shortest common length.

I then stumbled across this snippet about map in the manual:

map( function, list, …)
Apply function to every item of list and return a list of the results. If additional list arguments are passed, function must take that many arguments and is applied to the items of all lists in parallel; if a list is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple list arguments, map() returns a list consisting of tuples containing the corresponding items from all lists (a kind of transpose operation). The list arguments may be any kind of sequence; the result is always a list.

In other words is the function is None the resulting tuples are padded with None

>>> list=[[1,2,3],[4,5,6],[7,8,9,10]]
>>> print map(None,*list)
[(1, 4, 7), (2, 5, 8), (3, 6, 9), (None, None, 10)]

Now in-case you are looking at this wondering what the star (*) syntax is, it is called an “Arbitrary Argument List” and it’s useful here as it expands our list to pass each of the lists within the outer list as an arguments to zip and map.

Post Tools

Comments: Add yours

1. On August 7th, 2008 at 10:21 pm Raphael said:

Great. Thanks!

2. On December 4th, 2008 at 12:46 pm Batteries included has strong resonance « Yet another blog again said:

[...] Solution – Use Zip. [...]







XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



Using Loggerhead with mod_wsgi|(0)

Here’s a post I wrote over on the Project Fondue Blog about our use of Loggerhead with mod_wsgi under Apache. Loggerhead is the rather nice branch viewer for bazaar branches as used on Launchpad.net.

If you’re not already subscribed to the Project Fondue blog feed then I can recommend it, as there should be some interesting posts coming out of there in the coming months (yes I’m unashamedly biased!).

Ubuntu: Turn off changing workspace with mouse wheel|(1)

I found the changing with the workspace with the mouse wheel really annoying. To disable it go to System => Preferences => CompizConfig (available if the compizconfig-settings-manager package is installed) and uncheck “Viewport Switcher” which is under the “Desktop” heading.

Photos on Flickr

© Copyright 2004-10 Stuart Colville, all rights reserved. May contain traces of Muffin. Powered by WordPress. Hosting by Slicehost.com This page was baked in 0.592s.