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]]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With