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.
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.
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.
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.
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.
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)
l = list(zip(range(99), range(99))) # list of tuples to flatten
[item for sublist in l for item in sublist]
timeit result = 7.67 µs ± 129 ns per loop
flattened = [] list(flattened.extend(item) for item in l)
timeit result = 11 µs ± 433 ns per loop
list(sum(l, ()))
timeit result = 24.2 µs ± 269 ns per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With