2

Flattening lists of lists is a well-known problem but how does one flatten a list of lists of lists in the most pythonic way? My ultimate goal is to create a numpy array as follows:

[In]: mylist = [[[1,2,3], [4]], [[5,6], [7,8]]]
[Out]: array([[1, 2, 3, 4],
              [5, 6, 7, 8]])

but even just completely flattening into a long list will do (can be easily converted into the right-shaped array anyway). A typical output array will have dimensions (10000, 10) so looping through the rows-to-be is very inefficient. All ideas will be appreciated!

(edit) Best solution I can think of:

import itertools

for i in range(len(mylist)):
    mylist[i] = list(itertools.chain.from_iterable(mylist[i]))
np.array(mylist)
coaxialquantum
  • 135
  • 1
  • 6

1 Answers1

0

A possibility is to use numpy.append:

import numpy as np

rows = [[[1, 2, 3], [4]], [[5, 6], [7, 8]]]
result = np.array([np.append(value[0], value[1:]) for value in rows])

print(result)

Output

[[1 2 3 4]
 [5 6 7 8]]

The function numpy.append flattens value[1:]. One alternative is to use concatenate and ravel:

rows = [[[1], [2], [3]], [[4], [5], [6]]]
result = np.array([np.concatenate(value).ravel() for value in rows])
print(result)

Output

[[1 2 3]
 [4 5 6]]

The concatenate function join a sequence of arrays and np.ravel returns a contiguous flattened array. You could change np.ravel by np.flatten.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76