开发者

Making a flat list out of a multi-type nested list [duplicate]

开发者 https://www.devze.com 2023-03-15 15:27 出处:网络
This question already has answers here: Closed 11 years ag开发者_如何学Co. Possible Duplicate: Flatten (an irregular) list of lists in Python
This question already has answers here: Closed 11 years ag开发者_如何学Co.

Possible Duplicate:

Flatten (an irregular) list of lists in Python

I have the following list --

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

And I need to make it flat --

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

To do this, I am currently using a for loop with isinstance, with the number of loops being #nests - 1.

What woud be the simplest way to make the nested list flat? Thank you.

A similar question which deals with making a flat list out of nested lists (only) can be found here: Making a flat list out of list of lists in Python.


Hauled from webhelpers.misc.flatten

def flatten(iterable):
    """Recursively iterate lists and tuples.
    """
    for elm in iterable:
        if isinstance(elm, (list, tuple)):
            for relm in flatten(elm):
                yield relm
        else:
            yield elm

EDIT: The iterable test here is quite naive and can be improved by checking for the presence of __iter__ or an instance of the collections.Iterable abstract base class.

EDIT 2: @ChristopheD is absolutely correct, this is a dupe so head over to the linked question.


Try this:

def flat(mlist):
    result = []
    for i in mlist:
        if type(i) is list:
            result.extend(flat(i))
        else:
            result.append(i)
    return result
0

精彩评论

暂无评论...
验证码 换一张
取 消