【问题标题】:Remove excessive lists in python删除python中的过多列表
【发布时间】:2019-03-02 18:57:53
【问题描述】:

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

  {'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] 实际工作? (或找到完全不同的方法)

【问题讨论】:

  • 它不需要递归,迭代版本将避免过多的调用开销。我认为问题在于 x 是一个复制的范围变量。您可能需要返回 eleminate_excessive_nested_lists() 才能实际传递值。

标签: python list dictionary recursion


【解决方案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 带有工作代码和测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-06
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多