Transform "list of tuples" into a flat list or a matrix

garth picture garth · May 17, 2012 · Viewed 45k times · Source

With Sqlite, a "select..from" command returns the results "output", which prints (in python):

>>print output
[(12.2817, 12.2817), (0, 0), (8.52, 8.52)]

It seems to be a list of tuples. I would like to either convert "output" in a simple 1D array (=list in Python I guess):

[12.2817, 12.2817, 0, 0, 8.52, 8.52]

or a 2x3 matrix:

12.2817 12.2817
0          0 
8.52     8.52

to be read via "output[i][j]"

The flatten command does not do the job for the 1st option, and I have no idea for the second one... :)

Could you please give me a hint? Some thing fast would be great as real data are much bigger (here is just a simple example).

Answer

Joel Cornett picture Joel Cornett · May 17, 2012

By far the fastest (and shortest) solution posted:

list(sum(output, ()))

About 50% faster than the itertools solution, and about 70% faster than the map solution.