Manipulating lists in Python

Asked

Viewed 997 times

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 her like this:

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

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)

3

You are looking for the function extend that adds an iterable to a list. To apply it you need to use a loop/cycle that runs through your initial 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 example in Ideone

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

Browser other questions tagged

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