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.
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.
Or you can flatten the list like this:
reduce(lambda x,y:x+y, map(list, output))
In case of arbitrary nested lists(just in case):
def flatten(lst):
result = []
for element in lst:
if hasattr(element, '__iter__'):
result.extend(flatten(element))
else:
result.append(element)
return result
>>> flatten(output)
[12.2817, 12.2817, 0, 0, 8.52, 8.52]
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
This is what numpy
was made for, both from a data structures, as well as speed perspective.
import numpy as np
output = [(12.2817, 12.2817), (0, 0), (8.52, 8.52)]
output_ary = np.array(output) # this is your matrix
output_vec = output_ary.ravel() # this is your 1d-array
In Python 3 you can use the *
syntax to flatten a list of iterables:
>>> t = [ (1,2), (3,4), (5,6) ]
>>> t
[(1, 2), (3, 4), (5, 6)]
>>> import itertools
>>> list(itertools.chain(*t))
[1, 2, 3, 4, 5, 6]
>>>