Удалить лишние списки в Python - PullRequest
0 голосов
/ 02 марта 2019

У меня есть словарь, состоящий из вложенных списков и словарей.Некоторые из этих списков состоят только из одного элемента: другого списка.Я хочу сохранить элемент, но я хочу удалить бессмысленный одноэлементный список.Например, из

  {'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 голосов
/ 02 марта 2019

Здесь я попытался исправить вашу функцию с минимальными изменениями, насколько это возможно.Надеюсь, это поможет:

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

Ссылка на блокнот Google Colab с рабочим кодом и тестом.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...