python - Comment faire une liste plate d'une liste de listes

Mots clés : pythonlistmultidimensional-arrayflattenpython

meilleur 5 Réponses python - Comment faire une liste plate d'une liste de listes

vote vote

90

flat_list = [item for sublist in t for item in sublist] 
flat_list = [] for sublist in t:     for item in sublist:         flat_list.append(item) 
def flatten(t):     return [item for sublist in t for item in sublist] 
$ python -mtimeit -s't=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in t for item in sublist]' 10000 loops, best of 3: 143 usec per loop $ python -mtimeit -s't=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(t, [])' 1000 loops, best of 3: 969 usec per loop $ python -mtimeit -s't=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,t)' 1000 loops, best of 3: 1.1 msec per loop 
vote vote

86

import itertools  list2d = [[1,2,3], [4,5,6], [7], [8,9]] merged = list(itertools.chain(*list2d)) 
merged = list(itertools.chain.from_iterable(list2d)) 
vote vote

73

>>> l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] >>> sum(l, []) [1, 2, 3, 4, 5, 6, 7, 8, 9] 
vote vote

69

import functools import operator functools.reduce(operator.iconcat, a, []) 
out = [] for sublist in a:     out.extend(sublist) 
import functools import itertools import operator  import numpy as np import perfplot   def forfor(a):     return [item for sublist in a for item in sublist]   def sum_brackets(a):     return sum(a, [])   def functools_reduce(a):     return functools.reduce(operator.concat, a)   def functools_reduce_iconcat(a):     return functools.reduce(operator.iconcat, a, [])   def itertools_chain(a):     return list(itertools.chain.from_iterable(a))   def numpy_flat(a):     return list(np.array(a).flat)   def numpy_concatenate(a):     return list(np.concatenate(a))   def extend(a):     out = []     for sublist in a:         out.extend(sublist)     return out   b = perfplot.bench(     setup=lambda n: [list(range(10))] * n,     # setup=lambda n: [list(range(n))] * 10,     kernels=[         forfor,         sum_brackets,         functools_reduce,         functools_reduce_iconcat,         itertools_chain,         numpy_flat,         numpy_concatenate,         extend,     ],     n_range=[2 ** k for k in range(16)],     xlabel="num lists (of length 10)",     # xlabel="len lists (10 lists total)" ) b.save("out.png") b.show() 
vote vote

55

>>> from functools import reduce >>> l = [[1,2,3], [4,5,6], [7], [8,9]] >>> reduce(lambda x, y: x+y, l) [1, 2, 3, 4, 5, 6, 7, 8, 9] 
>>> import operator >>> l = [[1,2,3], [4,5,6], [7], [8,9]] >>> reduce(operator.concat, l) [1, 2, 3, 4, 5, 6, 7, 8, 9] 

Questions similaires