How to merge an array?

Asked

Viewed 5,079 times

1

I am writing a program that merges the values of two arrays, with the same amount of values. The program receives as input amount of values in each array. It then takes the values and at the end prints the intercalated values, as follows:

Entree:

3
2
7
5
9
6
8

Exit:

2
9
7
6
5
8

Like I’m doing:

quantidade = int(raw_input())
inicio = 0
lista1 = list()
while inicio < quantidade:
    valor = int(raw_input())
    inicio = inicio + 1
    lista1.append(valor)

My code creates a list of the values received, but I don’t know how to create the two lists, nor how to intermediate the values. How to proceed?

  • You want to join two lists?

  • I want to parse the values of the lists. The amount of values in each list must be provided by the user at the beginning. Example: List 1 = [1, 2, 3], List 2 = [4, 5, 6], List of intercalated values = [1, 4, 2, 5, 3, 6].

1 answer

4


You must make an interaction between two lists to be able to interlink them, one way to make this interaction between them is to get the interactor of the list with the method zip(), and separates the elements from them.

Take this example:

def intercala(L,L2):
    intercalada = []
    for a,b in zip(L, L2):
        intercalada.append(a)
        intercalada.append(b)
    return intercalada

lista1 = [1,2,3]
lista2 = [4,5,6]

listaIntercalada = intercala(lista1, lista2)

for i in listaIntercalada:
    print i

Exit:

1
4
2
5
3
6

Explanation

I have created a method responsible for bridging the lists intercala() which returns the intercalated list, the data that are passed to it as parameters are two lists, this way it is possible to get what you want.

See the documentation of the method zip() to learn more.

Browser other questions tagged

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