Howto: extract a 'column' from a list of lists into a new list?
bokr at oz.net
Wed Jul 2 11:04:13 CEST 2003
On Tue, 01 Jul 2003 20:07:58 -0500, John Hunter <jdhunter at ace.bsd.uchicago.edu> wrote:
>>>>>> "Bengt" == Bengt Richter <bokr at oz.net> writes:
> >>>> zip(*fields)
>That is amazingly helpful. I've often needed to transpose a 2d list,
>(mainly to get a "column" from an SQL query of a list of rows) and
>this is just the trick.
>I recently wrote a function to "deal" out a list of MySQLdb results,
>where each field was a numeric type, and wanted to fill numeric arrays
>with each column of results
>With your trick, eg, for a list of results from three numeric fields,
>I just have to do:
> a1, a2, a3 = map(array, zip(*results))
That looks neat. But it isn't really "my" trick (whatever that means ;-).
Anyway, IIRC, I learned it from a Martellibot post some time back ;-)
More information about the Python-list