How to merge an array?

1

I'm writing a program that merges the values of two arrays, with the same amount of values. The program receives as input the amount of values in each array. It then receives the values and, finally, prints the merged values, as follows:

Entry:

3
2
7
5
9
6
8

Output:

2
9
7
6
5
8

How do I do:

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 received values, but I do not know how to create the two lists, or how to merge the values. How to proceed?

    
asked by anonymous 10.04.2016 / 14:24

1 answer

4

You should make an interaction between two lists in order to merge them, one way to make this interaction between them is to get the interacator from the list with the zip() method, and separates the elements from them.

See 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

Output:

  

1
  4
  2
  5
  3   6

Explanation

I created a method responsible for merging the intercala() lists that returns the merged list, the data that is passed to it as parameters are two lists, in this way you can get what you want.

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

    
10.04.2016 / 18:26