Transform “list of tuples” into a flat list or a matrix

后端 未结 9 2005
北荒
北荒 2020-11-27 13:17

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.         


        
9条回答
  •  忘掉有多难
    2020-11-27 13:57

    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

提交回复
热议问题