How to flatten a list of lists of lists in python [duplicate]

℡╲_俬逩灬. 提交于 2019-12-10 12:00:30

问题


I've seen a couple answers on how to flatten lists of the form

[1,[1,2],[3]]    
print list(itertools.chain(*[1,[1,2],[3]]))  

but how do you flatten lists like this:

[[1],[[1,2],[3]]]

print list(itertools.chain(*[[1],[[1,2],[3]]]))
[1, [1, 2], [3]]

回答1:


I usually use this recipe:

import collections


def flatten(l):

    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, str):
            for sub in flatten(el):
                yield sub
        else:
            yield el


print(list(flatten([[1],[[1,2],[3]]])))
# [1, 1, 2, 3]


来源:https://stackoverflow.com/questions/29325503/how-to-flatten-a-list-of-lists-of-lists-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!