Skip to main content
 首页 » 编程设计

python之删除python中过多的列表

2024年11月24日17落叶

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

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

请您参考如下方法:

在这里,我已尝试以尽可能少的更改修复您的功能。希望这有助于:

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具有工作代码和测试。