简体   繁体   English

从元组列表中删除大多数嵌套列表括号

[英]Removing most nested list brackets from a list of tuples

I work with a 3D List and want to remove the most nested brackets and comma of the list.我使用 3D 列表并希望删除列表中最嵌套的括号和逗号。

My original list looks like this:我的原始列表如下所示:

[[[2.250922, 48.867699], [2.250805, 48.867744], [2.250688, 48.867699], [2.250688, 48.867611], [2.250805, 48.867566], [2.250922, 48.867611], [2.250922, 48.867699]], [[2.251038, 48.867832], [2.250922, 48.867877], [2.250805, 48.867832], [2.250805, 48.867744], [2.250922, 48.867699], [2.251038, 48.867744], [2.251038, 48.867832]]]

I like to remove the square brackets and the comma, which divides the values inside the brackets so it looks more like this:我喜欢删除方括号和逗号,它将括号内的值分开,所以看起来更像这样:

[[2.250922 48.867699, 2.250805 48.867744, 2.250688 48.867699, 2.250688 48.867611, 2.250805 48.867566, 2.250922 48.867611, 2.250922 48.867699], [2.251038 48.867832, 2.250922 48.867877, 2.250805, 48.867832, 2.250805 48.867744, 2.250922 48.867699, 2.251038 48.867744, 2.251038 48.867832]]

I already tried to use functions for flattening the list, but in that case only the outer brackets got removed.我已经尝试使用函数来展平列表,但在这种情况下,只有外括号被删除了。 Further, I tried to use following function:此外,我尝试使用以下功能:

new_list = [[item[0] for item in inner_list] for inner_list in outer_list]

Yet, in that instance I lose half of my values inside the brackets (all values with 48.xx).然而,在那种情况下,我在括号内丢失了一半的值(所有值为 48.xx 的值)。 Is there a solution to this problem?这个问题有解决方案吗?

try with this:试试这个:

    original_list = [[[2.250922, 48.867699], [2.250805, 48.867744], [2.250688, 48.867699], [2.250688, 48.867611], [2.250805, 48.867566], [2.250922, 48.867611], [2.250922, 48.867699]], [[2.251038, 48.867832], [2.250922, 48.867877], [2.250805, 48.867832], [2.250805, 48.867744], [2.250922, 48.867699], [2.251038, 48.867744], [2.251038, 48.867832]]]
    new_list = [[num for sub_l in l for num in sub_l] for l in original_list]
    print(new_list)

For nested lists, I use the following function:对于嵌套列表,我使用以下函数:

def flatten(iterable):
    for item in iterable:
        if isinstance(item, (list, tuple, set)):
            yield from flatten(item)
        else:
            yield item


flat_list = list(flatten(nested_list))

If you want to keep the structure [[list_1], [list_2]] instead of [list_1, list_2] , then:如果要保留结构[[list_1], [list_2]]而不是[list_1, list_2] ,则:

semi_flat_list = [list(flatten(item)) for item in nested_list]

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

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