Muffinresearch Labs by Stuart Colville

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

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







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>



Standalone mac battery charger|(0)

Got a spare mac battery? I’ve often wondered why up until now no-one’s produced a standalone charger so that you can charge batteries without having to plug them into the mac. Fortunately Fastmac.com have produced a standalone charger that allows you to do just that. and it’s compatible with iBooks, Powerbooks, macbooks and Macbook Pros. It’s also 110/200v. Exactly what I was looking for!

Django Admin Ominigraffle Stencil|(0)

Colleague Alex Lee has created a nice stencil for omingraffle with the Django Admin UI components, perfect for wireframing customised admin screens. For more details and to download the stencil see Alex’s Blog csensedesign.co.uk

Photos on Flickr

© Copyright 2004-08 Stuart Colville, all rights reserved. May contain traces of Muffin. Powered by WordPress. Hosting by 1&1 This page was baked in 0.701s.