To complement Miguel’s response, I show a way to implement the ordination he intends "in hand". It should be noted that in a real situation there is no need to do this, for various reasons, and its implementation will most likely be much less efficient than the native implementation already provided (as well as the one I demonstrate in this response).
For simplicity I chose the Selection Sort recalling that other algorithms will be more efficient such as Quicksort, Mergesort, Heapsort among others that ensure time complexity in the order of O(nlogn).
Example:
lista = [('Thiago', 30, 9.0), ('Maria', 28, 7.0), ('Ana', 30, 9.0)]
resultado = [i for i in lista] # passar tudo da lista para resultado
tamanho = len(resultado) # achar e guardar o tamanho
for i in range(0, tamanho): # para cada posição da lista
menor = i # pre-definir o menor como o elemento corrente
for j in range(i + 1, tamanho): # percorrer os restantes para achar o menor
# se este é menor
if resultado[j][2] < resultado[menor][2] or \
(resultado[j][2] == resultado[menor][2] and resultado[j][1] < resultado[menor][1]) or \
(resultado[j][1] == resultado[menor][1] and resultado[j][0] < resultado[menor][0]):
menor = j # guarda a posição
if resultado[i] != resultado[menor]: # se achou um menor diferente do corrente
# faz a troca de posição entre o corrente e o menor
temp = resultado[menor]
resultado[menor] = resultado[i]
resultado[i] = temp
print(resultado)
The if
within the second for
is what defines the way the elements are ordered because it is what defines which is the least element for that position. Note that I started by comparing the position [j][2]
that is to say in the current element the position 2
average:
if resultado[j][2] < resultado[menor][2]
If it is not smaller but equal, it will now compare with another value of the same element, the age that is in the position 1
:
or \
(resultado[j][2] == resultado[menor][2] and resultado[j][1] < resultado[menor][1])
And if the position 1
is equal compared by the name in the position 0
:
or \
(resultado[j][1] == resultado[menor][1] and resultado[j][0] < resultado[menor][0]):
See the example in Ideone
Hello Anthony, I continued having difficulties in assembling my code, I tried to ask the same question using the same link yesterday but I could not, I will try to improve, I decided to try one more question in relation to the code, but now I will gather the answers and study the best way to finish it, as soon as I can publish the final result, I thank you all .
– Bruno
Hello Bruno please do not duplicate questions with the same content. Between the answer in the original question and the two answers in that question you have three (quite similar) answers on how to sort your list and create the ranking correctly ordered with all fields. If the proposed solutions are unclear or do not meet your problem for some reason it is worth refining your question so that we can understand exactly what you are struggling with.
– Anthony Accioly