Manipulating list of lists in Python

1

I have a list like this:

 Lista_A = [['de','do','da','ou'],['ae','ay','yhh','oo'],['ow','pa','la','for']]

How do I leave it like this:

Lista_A_new = ['de','do','da','ou','ae','ay','yhh','oo','ow','pa','la','for']
    
asked by anonymous 08.10.2017 / 23:08

2 answers

5

Solution # 1:

Lista_A = [['de','do','da','ou'],['ae','ay','yhh','oo'],['ow','pa','la','for']]

Lista_A_new = [item for sublista in Lista_A for item in sublista]

print(Lista_A_new)

Solution # 2:

Lista_A = [['de','do','da','ou'],['ae','ay','yhh','oo'],['ow','pa','la','for']]

Lista_A_new = sum( Lista_A, [] )

print(Lista_A_new)

Solution # 3:

import numpy as np

Lista_A = [['de','do','da','ou'],['ae','ay','yhh','oo'],['ow','pa','la','for']]

Lista_A_new = np.concatenate(Lista_A)

print(Lista_A_new)

Solution # 4:

import itertools

Lista_A = [['de','do','da','ou'],['ae','ay','yhh','oo'],['ow','pa','la','for']]

Lista_A_new = list(itertools.chain(*Lista_A))

print(Lista_A_new)
    
08.10.2017 / 23:24
3

You are looking for the extend function that adds an iterable to a list. To apply it you need to use a loop / loop that runs through your home lists.

Lista_A = [['de','do','da','ou'],['ae','ay','yhh','oo'],['ow','pa','la','for']]

Lista_A_new  = []

for lista in Lista_A: #for percorre cada uma das sub listas iniciais
    Lista_A_new.extend(lista) #extend aqui adiciona todos os elementos de cada sub-lista

print(Lista_A_new) #['de', 'do', 'da', 'ou', 'ae', 'ay', 'yhh', 'oo', 'ow', 'pa', 'la', 'for']

See the Ideone example

I also advise you to take a look at the python writing conventions , since the variable names you used do not follow the convention.

    
08.10.2017 / 23:17