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

后端 未结 9 1963
北荒
北荒 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:40

    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.

    0 讨论(0)
  • 2020-11-27 13:46

    Or you can flatten the list like this:

    reduce(lambda x,y:x+y, map(list, output))
    
    0 讨论(0)
  • 2020-11-27 13:47

    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]
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-27 13:57

    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
    
    0 讨论(0)
  • 2020-11-27 13:58

    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]
    >>> 
    
    0 讨论(0)
提交回复
热议问题