3

I've already searched SO for how to flatten a list of lists (i.e. here:Making a flat list out of list of lists in Python) but none of the solutions I find addresses flattening a list of lists of lists to just a list of lists.

I have:

my_list = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ]

I want:

my_list = [ [1,2,3,4,5], [9,8,9,10,3,4,6], [1] ]

The solution should work for a list of floats as well. Any suggestions?

Community
  • 1
  • 1
user2483176
  • 317
  • 1
  • 10
  • 21

4 Answers4

9

If we apply the logic from this answer, should not it be just:

In [2]: [[item for subsublist in sublist for item in subsublist] for sublist in my_list]
Out[2]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]]

And, similarly via itertools.chain():

In [3]: [list(itertools.chain(*sublist)) for sublist in my_list]
Out[3]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]]
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

This is an inside-out version of fl00r's recursive answer which coincides more with what OP was after:

def flatten(lists,n):
    if n == 1:
        return [x for xs in lists for x in xs]   
    else:
        return [flatten(xs,n-1) for xs in lists]


>>> flatten(my_list,1)
[[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4, 6], [1]]
>>> flatten(my_list,2)
[[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]]
John Coleman
  • 51,337
  • 7
  • 54
  • 119
0

You could use this recursive subroutine

def flatten(lst, n):
  if n == 0:
    return lst

  return flatten([j for i in lst for j in i], n - 1)

mylist = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ]
flatten(mylist, 1)
#=> [[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4, 6], [1]]
flatten(mylist, 2)
#=> [1, 2, 3, 4, 5, 9, 8, 9, 10, 3, 4, 6, 1]
fl00r
  • 82,987
  • 33
  • 217
  • 237
0

For this particular case,

In [1]: [sum(x,[]) for x in my_list]
Out[1]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]]

is the shortest and the fastest method:

In [7]: %timeit [sum(x,[]) for x in my_list]
100000 loops, best of 3: 5.93 µs per loop
B. M.
  • 18,243
  • 2
  • 35
  • 54
  • Not i's _not_ the fastest method! don't use `sum` for lists. It's highly inefficient on big lists (quadratic effect): https://stackoverflow.com/questions/41772054/why-sum-on-lists-is-sometimes-faster-than-itertools-chain – Jean-François Fabre Mar 21 '18 at 09:29
  • Hence the precaution : For this particular case. – B. M. Mar 21 '18 at 18:24