Skip to content Skip to sidebar Skip to footer

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: [[

Solution 1:

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)) forsubin 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.

Solution 2:

>>>from operator import add>>>lists = [ [ [1],[2],[3],[4], [5] ],   [ [6],[7],[8] ] , [ [11],[12] ] ]>>>[reduce(add, lst) for lst in lists]
[[1, 2, 3, 4, 5], [6, 7, 8], [11, 12]]

This is not a very efficient, as it rebuilds a list each time add is called. Alternatively you can use sum or a simple list comprehension, as seen in the other answers.

Solution 3:

Because this question looks fun! I used a recursive function that unpacks a list if it only has one value.

def make_singular(l):
    try:
        iflen(l) == 1:
            return l[0]
        else:
            return [make_singular(l_) for l_ in l]
    except:
        return l

nest = [ [ [1],[2],[3],[4], [5] ], [ [6],[7],[8] ] , [ [11],[12] ] ]
make_singular(nest)

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

Solution 4:

Try this:

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

l = [ [x[0] forxin s if x[0] is not None] forsin l]

Solution 5:

How about np.squeeze?

Remove single-dimensional entries from the shape of an array.

arr = [ [ [1],[2],[3],[4], [5] ], [ [6],[7],[8] ] , [ [11],[12] ] ]
>>> arr
[[[1], [2], [3], [4], [5]], [[6], [7], [8]], [[11], [12]]]
>>> [np.squeeze(i) for i in arr]
[array([1, 2, 3, 4, 5]), array([6, 7, 8]), array([11, 12])]

Not necessarily the innermost (ie independent of how many dimensions) dimension though. But your question specifies "list of lists"

Post a Comment for "How To Remove The Innermost Level Of Nesting In A List Of Lists Of Varying Lengths"