I have a list which consists of many lists. Here is an example,
[
[Obj, Obj, Obj, Obj],
[Obj],
[Obj],
[
[Obj,Obj],
[Obj,Obj,Obj]
]
]
Is there a way to join all these items together as one list, so the output will be something like
[Obj开发者_如何学JAVA,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj]
Yes, here's one way to do it:
def flatten(lst):
for elem in lst:
if type(elem) in (tuple, list):
for i in flatten(elem):
yield i
else:
yield elem
Please note, this creates a generator, so if you need a list, wrap it in list()
:
flattenedList = list(flatten(nestedList))
Stolen from MonkeySage, here:
def iter_flatten(iterable):
it = iter(iterable)
for e in it:
if isinstance(e, (list, tuple)):
for f in iter_flatten(e):
yield f
else:
yield e
精彩评论