如何在python中展平列表列表 [英] How to flatten a list of lists of lists in python

查看:107
本文介绍了如何在python中展平列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了一些有关如何展平表单列表的答案

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]]

推荐答案

我通常使用此食谱:

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]

这篇关于如何在python中展平列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆