Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

python - 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]]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...