Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the innermost level of nesting in a list of lists of varying lengths

I'm trying to remove the innermost nesting in a list of lists of single element length lists. Do you know a relatively easy way (converting to NumPy arrays is fine) to get from:

[[[1], [2], [3], [4], [5]], [[6], [7], [8]], [[11], [12]]]

to this?:

[[1, 2, 3, 4, 5], [6, 7, 8], [11, 12]]

Also, the real lists I'm trying to do this for contain datetime objects rather than ints in the example. And the initial collection of lists will be of varying lengths.

Alternatively, it would be fine if there were nans in the original list so that the length of each list is identical as long as the nans aren't present in the output list. i.e.

[[[1], [2], [3], [4], [5]], 
 [[6], [7], [8], [nan], [nan]], 
 [[11], [12], [nan], [nan], [nan]]]

to this:

[[1, 2, 3, 4, 5], [6, 7, 8], [11, 12]]
like image 297
Matthew Borish Avatar asked Mar 11 '23 08:03

Matthew Borish


1 Answers

If the nesting is always consistent, then this is trivial:

In [2]: import itertools

In [3]: nested = [ [ [1],[2],[3],[4], [5] ], [ [6],[7],[8] ] , [ [11],[12] ] ]

In [4]: unested = [list(itertools.chain(*sub)) for sub in nested]

In [5]: unested
Out[5]: [[1, 2, 3, 4, 5], [6, 7, 8], [11, 12]]

Note, the solutions that leverage add with lists are going to give you O(n^2) performance where n is the number of sub-sublists that are being merged within each sublist.

like image 160
juanpa.arrivillaga Avatar answered Apr 06 '23 20:04

juanpa.arrivillaga