You can correlate list elements lista1
and lista2
through function zip
. Also, you can concatenate lists using the operator +
. So if you create a new list - using list comprehensions - in which each element is e1[:2] + e2 + e1[-1:]
you get what you want:
>>> lista1 = [['carlos','10','cenouras','carro','agora'],['duarte','34','couves','bus','agora']]
>>> lista2 = [['11:30', '12:00'],['13:00', '13:30']]
>>> listaNova = [e1[:2] + e2 + e1[-1:] for e1, e2 in zip(lista1, lista2)]
>>> listaNova
[['carlos', '10', '11:30', '12:00', 'agora'], ['duarte', '34', '13:00', '13:30', 'agora']]
(Note that I used e1[-1:]
instead of simply e1[-1]
because I want a list with an element, and not only the element)
If you want to do "in full" (i.e. using loops, append
and extend
), would look like this:
listaNova = []
for e1, e2 in zip(lista1, lista2):
item = []
listaNova.append(item) # append acrescenta um item na lista
item.extend(e1[:2]) # extend acrescenta os itens do argumento na lista
item.extend(e2)
item.append(e1[-1]) # como é um único elemento, pode usar append
Finally, if you want to avoid the zip
, can make a normal loop over the list contents (beware, make sure the lists are equal in size):
listaNova = []
for i in range(len(lista1)): # i vai de 0 a "tamanho da lista" - 1
item = []
listaNova.append(item)
e1 = lista1[i]
e2 = lista2[i]
item.extend(e1[:2])
item.extend(e2)
item.append(e1[-1])
But note how the code gets extended, while the first method does the same thing using a single line of code... As you master these concepts (mainly list comprehension, one of the most powerful features of language) get used to using them in place of more verbose constructions, when appropriate.
You can’t explain it to me in a simpler way, using the append and the extend ?
– CSAnimor
I was wrong about one thing, I edited it like I wanted it. on the listNew final wanted it to be like this:
listaNova = [['carlos', '10', '11:30', '12:00','agora'], ['duarte', '34', '13:00', '13:30','agora']]
– CSAnimor
@Stinrose Of course, I edited my answer in two alternative ways. The option with understandings is much more concise, however, consider giving a studied it and your code will be much more "dry". :)
– mgibsonbr
Thank you ! : ) that’s right
– CSAnimor