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
精彩评论