简体   繁体   English

取消嵌套嵌套列表

[英]Un-nesting nested lists

Hi I was wondering how I could un-nest a nested nested list.您好,我想知道如何解除嵌套的嵌套列表。 I have:我有:

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

I would like to to look as follows:我想看如下:

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

How to do it?怎么做?

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

For multiple nestings: 对于多个嵌套:

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

A test: 一个测试:

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

I found another solution that might be easier and quicker here and also mentioned here .我在这里找到了另一个可能更容易、更快捷的解决方案,也提到了这里

from itertools import chain

nested_list = [[[1,2,3]], [[4,5,6]], [[7,8,9]]]
my_unnested_list = list(chain(*nested_list))
print(my_unnested_list)

which results in your desired output as:这导致您想要的 output 为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM