I would use a list of lists instead of variables n1
, n2
, etc (such as probably is an exercise, and exercises tend to have artificial limitations like "cannot use [useful native resource that makes it easier to solve the problem]", I understand that you may not want to use this, but anyway I leave registered here the alternative).
def ler_dados_lista(indice_lista, tamanho):
lista = []
for n in range(tamanho):
lista.append(int(input(f'Digite o {n + 1}° elemento da {indice_lista + 1}ª lista: ')))
print('=' * 40)
return lista
listas = []
for i in range(3):
listas.append(ler_dados_lista(i, 10))
intercalados = []
for elementos in zip(*listas):
intercalados.extend(elementos)
print(f'Intercalando as listas 1, 2 e 3 temos:\n{intercalados}')
The function that reads the data from a list returns this list, and so I can add it to the list of lists using a for
simple. At the end, the variable listas
will be a list containing the 3 lists that have been read.
Then to create the list with the interleaved elements, I use zip
, that serves to go through several lists at once (just what you want to do).
The asterisk before listas
serves to make the unpacking, that is to say, zip(*listas)
is the same as zip(listas[0], listas[1], listas[2])
, with the difference being more succinct and mainly working without I need to know the amount of lists.
At each iteration, the variable elementos
will be a tuple containing the elements of each of the lists. In the first iteration, it will have the first element of each list, in the second iteration, the second element and so on.
At last, I use extend
to add all elements at once (instead of calling append
several times).
Also note that you can create an empty list using []
.
To make it more succinct and pythonic, you can exchange the loops above by list comprehensions:
def ler_dados_lista(indice_lista, tamanho):
lista = [ int(input(f'Digite o {n + 1}° elemento da {indice_lista + 1}ª lista: ')) for n in range(tamanho) ]
print('=' * 40)
return lista
listas = [ ler_dados_lista(i, 10) for i in range(3) ]
from itertools import chain
intercalados = list(chain.from_iterable(elementos for elementos in zip(*listas)))
print(f'Intercalando as listas 1, 2 e 3 temos:\n{intercalados}')
You could also do so (the difference is it won’t print a lot of "="
between messages - if this is desired, then keep the function ler_dados_lista
):
listas = [
[ int(input(f'Digite o {n + 1}° elemento da {i + 1}ª lista: ')) for n in range(10) ]
for i in range(3)
]