1

嗨,我想知道如何取消嵌套嵌套的嵌套列表。我有:

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

我想看起来如下:

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

怎么做?

4

2 回答 2

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]]
于 2013-10-03T22:12:07.977 回答
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]]
于 2013-10-03T22:22:49.257 回答