简体   繁体   中英

Python: how to generate a list of "flattened" lists out of a big nested list

Let us say I have a list like the following:

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

I want to know how to flatten this list in the following manner:

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

Putting it into words, I want to know how to generate a list out of each of the levels of the main list, each list generated being a flattened version of all its sublists.

EDIT:

If the method is a left-recursion one, it is likely that the outputted list will have the lists in the following order (and not the order above):

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

You could use a recursive generator function:

def yield_and_flatten(nested):
    """Yield sublists and flatten, recursively

    Produces a boolean and list on each yield; the boolean
    flags a merge; sublists are merged just once then
    passed down the recursion tree.

    """
    if not isinstance(nested, list):
        yield True, nested
        return
    res = []
    for elem in nested:
        for extend, sub in yield_and_flatten(elem):
            if isinstance(sub, list):
                if extend:
                    res.extend(sub)
                yield False, sub
            else:
                res.append(sub)
    yield True, res

This passes on sublists before extending the current level.

Demo:

>>> sample = [1, 2, [3, 4, [5, 6]], [7, 8], 9]
>>> for _, res in yield_and_flatten(sample):
...     print res
... 
[5, 6]
[3, 4, 5, 6]
[7, 8]
[1, 2, 5, 6, 3, 4, 5, 6, 7, 8, 9]
>>> mlist = [1, 2, 3, [[4, [5, 6]], 7], 8, 9]
>>> for _, res in yield_and_flatten(mlist):
...     print res
... 
[5, 6]
[4, 5, 6]
[4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM