取消嵌套嵌套列表

时间:2013-10-03 22:11:09

标签: python

您好我想知道如何取消嵌套嵌套嵌套列表。我有:

list = [[[1,2,3]], [[4,5,6]], [[7,8,9]]]

我想看看如下:

new_list = [[1,2,3], [4,5,6], [7,8,9]]

怎么做?

2 个答案:

答案 0 :(得分:11)

>>> L = [[[1,2,3]], [[4,5,6]], [[7,8,9]]]
>>> [x[0] for x in L]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

答案 1 :(得分:1)

对于多个嵌套:

def unnesting(l):
    _l = []
    for e in l:
        while isinstance(e[0], list):
            e = e[0]
        _l.append(e)
    return _l

测试:

In [24]: l = [[[1,2,3]], [[[[4,5,6]]]], [[[7,8,9]]]]
In [25]: unnesting(l)
Out[25]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]