Python - Transforming lists into a single list

Asked

Viewed 908 times

2

How can I turn a list into a single list?

I need to turn this:

lista = [["Danilo","Gilson"],["Eduarda",["Costa","Otávio"]]]

therein:

lista = ["Danilo","Gilson","Eduarda","Costa","Otávio"]
  • https://answall.com/questions/164539/como-unir-v%C3%A1rias-listas-em-uma-matriz this would help you Danilo ?

  • No, my doubt is similar to this one, but it still hasn’t solved my problem https://answall.com/questions/131258/converter-lista-de-lists-em-uma-s%C3%B3-list

  • 1

2 answers

1

I tried to abstract to a function and one of the forms would be this:

def lista_unica(lista):
    result = []
    for item in lista:
        if (isinstance(item, (list, tuple))):
            result = lista.extend(item)
        else:
            result.append(item)
    return result


>>> lista = [["Danilo","Gilson"],["Eduarda",["Costa","Otávio"]]]
>>> print(lista_unica(lista)) 
['Danilo', 'Gilson', 'Eduarda', 'Costa', 'Otávio']

Another way would be to use recursion and make only calls to the method append.

1

Using recursiveness and comprehensilist on looks good short:

def lista_simples(lista):
    if isinstance(lista, list):
        return [sub_elem for elem in lista for sub_elem in lista_simples(elem)]
    else:
        return [lista]

lista = [["Danilo","Gilson"],["Eduarda",["Costa","Otávio"]]]
resultado = lista_simples(lista)
print(resultado) # ['Danilo', 'Gilson', 'Eduarda', 'Costa', 'Otávio']

Watch it work on Ideone

For simplicity I left only the test with the guy list. If you want the function to work for any iterable you can switch to isinstance(lista, Iterable) but you’ll have to disregard when you’re a string which is also an eternal. In that case the ideal would be then:

if isinstance(lista, Iterable) and not isinstance(lista, str):

And adding the import to the Iterable

from collections import Iterable

Browser other questions tagged

You are not signed in. Login or sign up in order to post.