在python中删除过多的列表

时间:2019-03-02 18:57:53

标签: python list dictionary recursion

我有一本由嵌套列表和字典组成的字典。其中一些列表仅包含一个元素:另一个列表。我想保留该元素,但是我想删除无意义的单元素列表。例如。来自

  {'geojson': [{'geometry': {'coordinates': [[[5., 52.],
                                             [5., 52.],
                                             [5., 52.],
 ]],
                            'type': 'Polygon'},
               'properties': {},
               'type': 'Feature'}]},

我想拥有

  {'geojson': {'geometry': {'coordinates': [[5., 52.],
                                             [5., 52.],
                                             [5., 52.],
 ],
                            'type': 'Polygon'},
               'properties': {},
               'type': 'Feature'}},

我尝试了一个递归函数。它可以正确识别碎片,但返回的参数不变。

def eliminate_excessive_nested_lists(x):

    if isinstance(x,list):
        if len(x) == 1:
            x = x[0]  #I tried x[:] = x[0] but it works neither 
            eliminate_excessive_nested_lists(x)
        else:
            for element in x:
                eliminate_excessive_nested_lists(element)
    elif isinstance(x,dict):
        for key in x.keys():   
            eliminate_excessive_nested_lists(x[key])
    return x

我如何拨打电话 x = x [0] 实际工作? (或找到完全不同的方法)

1 个答案:

答案 0 :(得分:1)

在这里,我尝试通过最少的更改来修复您的功能。希望这会有所帮助:

def eliminate_excessive_nested_lists(x):

    if isinstance(x,list):
        # Case 1: If x itself is list and is nested with 1 element
        # unpack and call the function again
        if len(x) == 1:
            x = x[0]
            eliminate_excessive_nested_lists(x)
        else:
            # Case 2: if list has multiple elements
            # call the function indivually on each element and store in a 
            # seperate list. Copy the new list to old list
            # Note: Previously you were setting x = eliminate(element)
            # which was wrong since you were storing x as unpacked version of 
            # the elements
            temp_list = []
            for element in x:
                temp_list.append(eliminate_excessive_nested_lists(element))
            x = temp_list
    elif isinstance(x,dict):
        # Case 3: If x is dictionary, then for each key, set it's value to
        # x[key] = eliminate(x[key])
        # Note: previously you were setting this as x = eliminate(x[key])
        # which was wrong since you were setting x as unpacked version of x[key]
        for key in x.keys():
            x[key] = eliminate_excessive_nested_lists(x[key])

    return x

Link to Google Colab notebook,包含有效的代码和测试。