Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

With Sqlite, a select .. from command returns the results output, which prints:

>>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 to a simple list:

[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...

A fast solution would be appreciated, as the real data is much bigger.

like image 490
garth Avatar asked May 17 '12 09:05

garth


People also ask

How do you flatten a tuple list?

One method to flatten tuples of a list is by using the sum() method with empty lust which will return all elements of the tuple as individual values in the list. Then we will convert it into a tuple. Method 2: Another method is using a method from Python's itertools library.

How do you change a list of tuples to a list?

If you're in a hurry, here's the short answer:Use the list comprehension statement [list(x) for x in tuples] to convert each tuple in tuples to a list. This also works for a list of tuples with a varying number of elements.

How do you transform a tuple?

To convert a tuple into list in Python, call list() builtin function and pass the tuple as argument to the function. list() returns a new list generated from the items of the given tuple.


2 Answers

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.

like image 127
Joel Cornett Avatar answered Sep 19 '22 10:09

Joel Cornett


List comprehension approach that works with Iterable types and is faster than other methods shown here.

flattened = [item for sublist in l for item in sublist] 

l is the list to flatten (called output in the OP's case)


timeit tests:

l = list(zip(range(99), range(99)))  # list of tuples to flatten 

List comprehension

[item for sublist in l for item in sublist] 

timeit result = 7.67 µs ± 129 ns per loop

List extend() method

flattened = [] list(flattened.extend(item) for item in l) 

timeit result = 11 µs ± 433 ns per loop

sum()

list(sum(l, ())) 

timeit result = 24.2 µs ± 269 ns per loop

like image 39
Gman Avatar answered Sep 20 '22 10:09

Gman