Associate two lists in python

Asked

Viewed 1,958 times

2

Associate two lists, a car name list and another color list and each containing n elements:

listaCarros = ["gol","uno","corsa","palio","idea"]
listaCores = ["branco","verde","preto","cinza","azul"]

with the output in this format:

"The goal is white"

I did the following:

n=0

while n <= 5:

    print("\nO", end=' ')
    print(listaCarros[n],end=' é ')
    print(listaCores[n])
    n = n + 1

worked, but this message appeared:

Traceback (Most recent call last): "file path" line 286, in print(listCarros[n],end=' is ') Indexerror: list index out of range

would have a better way of doing that?

  • @Miguel is very simple.... Serie listaCarros = ["gol","Corsa","Palio"] and other colors in the same way. And in case associate the two just to print in that format, worked out the way I did, but is giving this msg of Indexerror and if by chance there is a better way to do it

  • I’m building an answer William

1 answer

5


The condition <= 5 is wrong, because if the lists have 5 elements only have between 0 and 4 indices (because these start at 0), try this version of the code while n < 5, or better, while n < len(listaCarros): .

That said, here’s a version more pythonica and with fewer lines, the 'best way':

listaCores = ['azul', 'vermelho', 'verde', 'laranja', 'branco', 'preto']
listaCarros = ['mazda', 'toyota', 'honda', 'pegeot', 'mercedez', 'BMW']
text = ''
for carro, cor in zip(listaCarros, listaCores):
    text += '\nO {} é {}'.format(carro, cor)
print(text)

DEMONSTRATION

To do as you were doing (with while) using this example (you need to be careful that the lists run the same number of elements, or construct the cycle based on the list with fewer elements):

listaCores = ['azul', 'vermelho', 'verde', 'laranja', 'branco', 'preto']
listaCarros = ['mazda', 'toyota', 'honda', 'pegeot', 'mercedez', 'BMW', 'saf', 'safs']

n = 0
text = ''
min_list = min(len(listaCores), len(listaCarros))
while n < min_list: # fazes isto caso nao tenhas a certeza que as listas tem o mesmo num de elementos
    text += '\nO {} é {}'.format(listaCarros[n], listaCores[n])
    n += 1
print(text)

DEMONSTRATION

  • that’s right... cool... is because I’m starting now in python and for example in C, if I put printf("O %s eh %s", arrayCarro[i], arrayCor[i]); and I print it in the standard... but ein python wanted to see if there was another way to format this output other than the way I did... I’m going to test it this way you did it!

  • Got it, bro! Thanks a lot.

  • Nothing @Williamhenrique , I added demonstrations to see, of both constructions

Browser other questions tagged

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