Top 3 the biggest numbers in the list and their indexes

Asked

Viewed 331 times

2

I have the list [5, 7, 2]. I need to create another list containing the indexes in this list, ordered so that the first index corresponds to the largest element in the list, the second corresponds to the second largest and so on - i.e., [1, 0, 2].

I could only show one number on the list at a time:

Index : 1

Numbers: 7

What I don’t understand is how to ride the for to display the indexes and their values.

lista = [5, 7, 2]

ind_num = lista.index(max(lista))

print('Maior elemento: ',max(lista))

print('Indice: ', (ind_num))
  • Luke, could you be clearer? Each element of a list (which I believe should be your case, has its own index, starting from scratch). Edit: I understood your case, I will elaborate the answer.

  • The elements of a list are their values per list = [5, 7, 2], the elements of this list are 5, 7, 2 and their incidence starting with 0 or the largest are in indices 1, 0, 2

1 answer

5


An alternative is:

lista = [5, 7, 2]
indices = sorted(range(len(lista)), key=lambda i: lista[i], reverse=True)
print(indices) # [1, 0, 2]

range(len(lista)) creates a sequence of all indexes in the list (in this case, the numbers 0, 1 and 2).

Next sorted orders these indices, but instead of taking into account their value, he considers their respective value in the original list - that’s what the lambda past to key makes: for each index i, the value that will be taken into account in the ordering is lista[i].

At last we use reverse=True so that he orders from the highest value to the lowest.

The result is the list [1, 0, 2].

Browser other questions tagged

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