How to add or concatenate data from a list?

1

Cordial greeting.

I have a list with str inside it in the following way:

 l1=['hola  estas','como  Carol','esta  tu   ','aqui  papa ']

and I want something like this to stay:

  l2=['hola-como',  'estas-Carol','esta-aqui', 'tu-papa']

Each str of the list l1 has the same length and each word is separated for the same spaces.

Thank you for your attention.

    
asked by Yeison Ordoñez 27.04.2016 в 19:06
source

2 answers

3

I'm not sure how you expect to combine the words of each element str . Suppose you want to combine in pairs, two by two:

l1=['hola  estas','como  Carol','esta  tu   ','aqui  papa ']

palabras = [s.split() for s in l1]

l2 = [ x+"-"+y for i in range(0,len(l1),2)
                for (x,y) in zip(palabras[i],palabras[i+1]) ]

As I put you in a comment, the code does what you ask. It serves for any number of elements and any number of words per element. But you will say if it is what you were looking for.

    
answered by 28.04.2016 / 02:46
source
1

This is a way to achieve what you want for any number of elements:

l1 = ['hola  estas','como  Carol','esta  tu   ','aqui  papa ']
#Creamos un array donde almacenamos el resultado.
l2 = []
#Dos arrays para almacenar textos de la izquierda y derecha de cada elemento el arreglo original.        
aLeft = []
aRight = []

#Agrega los textos a su correspondiente arreglo, aLeft para textos izquierda, aRight para textos derecha.     
for i in l1:
    aLeft.append(i.split()[0])
    aRight.append(i.split()[1])

for i in range(0, len(aLeft), 2): 
    l2.append(aLeft[i] + "-" + aLeft[i+1])
    l2.append(aRight[i] + "-" + aRight[i+1])

print l2

with a result:

  ['hola-como', 'estas-Carol', 'esta-aqui', 'tu-papa']
    
answered by 27.04.2016 в 19:43