Do extend list to another list

1

Well I have two lists of lists, list1 and list2:

lista1 = [['carlos','10','cenouras','carro','agora'],['duarte','34','couves','bus','agora']] 

lista2 = [['11:30', '12:00'],['13:00', '13:30']]

What I want is to create a new list with the first 2 elements of each list within list1, getting: listaNova = [['carlos', '10'], ['duarte', '34']]

Next, to each list within the listNew I want to add a list from list2, getting:

listaNova = [['carlos', '10', '11:30', '12:00'], ['duarte', '34', '13:00', '13:30']]

Finally I want to add the last element of list1:

listaNova = [['carlos', '10', '11:30', '12:00','agora'], ['duarte', '34', '13:00', '13:30','agora']]

What I already have is this:

listaNova =[]

for i in lista1:
   nomes = i[:2]
   listaNova.append(nomes)

But now I do not know how to extend the rest ..

    
asked by anonymous 09.12.2015 / 00:50

1 answer

2

You can correlate the elements of lists lista1 and lista2 through the function zip . In addition, you can concatenate lists by using the + operator. So if you create a new list - using list comprehensions - where 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, not just the element)

If you want to do it "extensively" (i.e. using loops, append and extend ), it 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 zip , you can make a normal loop over the indexes of lists (be careful that lists have equal 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 notice how extensive the code is, while the first method does the same thing using a single line of code ... As you master these concepts (especially list comprehension, one of the most powerful features of language ) become accustomed to using them instead of more verbose constructs, when appropriate.

    
09.12.2015 / 04:58