Compare values in a list of tuples

Asked

Viewed 776 times

0

 lista  = [('Maria', 28, 7.0), ('Ana', 30, 9.0), ('Thiago', 30, 9.0)]
 resultado = []
 for i in lista:
    if i[2]<i[2]+1:
        resultado.append(i[0])
 print(resultado)

Correct exit: Ana, Thiago, Maria

My way out is Maria, Ana , Thiago. Which gives us that no comparison was made with the mean values and then age and name. I would like a help how I can compare the values of this list and print in order, first comparison by average if equals step to age if age equals step to name, I’m two weeks trying to solve this problem I’m having a lot of difficulties.

  • 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 .

  • 1

    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.

2 answers

4

Two weeks is a long time since you can solve in 1/2 lines d:

lista = [('Thiago', 30, 9.0), ('Maria', 28, 7.0), ('Ana', 30, 9.0)]
ordered = sorted(lista, key=lambda x: (x[2], x[1], x[0]))
print(ordered) # [('Maria', 28, 7.0), ('Ana', 30, 9.0), ('Thiago', 30, 9.0)]

DEMONSTRATION

If you want it in reverse order:

...
ordered = sorted(lista, key=lambda x: (x[2], x[1], x[0]), reverse=True)
# [('Thiago', 30, 9.0), ('Ana', 30, 9.0), ('Maria', 28, 7.0)]
...

The trick is in the argument key the value of which is a function of which you can define by which value(s) you should sort.

DOCS

  • Thanks friend for the answer, the problem is that I can not use ' Sort' and 'Sorted', I have to do in hand, is this my difficulty, I tried if,for but I can not achieve my goal. I’m in the fight.

  • I have to make comparisons between average, age and if these are equal I have to sort the names in alphabetical order.

  • 2

    @Runo, you did not specify in the question that you could not use the function sorted. In such cases you need to make it very explicit.

  • @Brunosilva Anderson is right, in the 'real world' would be as it was done, for didactic reasons as yours should have specified that, I would not have given this answer if I knew that was the case

  • Personal I apologize for not having put correctly my question I will try to improve more and more, thanks for the attention of the gentlemen, I will continue in the fight.

  • I would like a help, I can add the notes and generate this list of tuples with the name , age and media but I can’t compare the medias and if the medias are equal I have to compare the ages so that higher age first candidate.

Show 1 more comment

2

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

  • Hi Isaac. The if internal establishing position-unpacking rules the position is unnecessary. By default, when comparing tuples, the operator < already unpacks equal values from left to right. That is, to sort through multiple criteria just rearrange the tuple to contain the average in the first position, age of the second, and name in the third. See my answer in the original question of the OP: https://answall.com/a/289780/100

  • @Anthonyaccioly Thanks for the comment. I didn’t really know about this native tuple comparison detail, but it actually makes the algorithm simpler.

  • Thank you very much for the answer, I will fight to try to get to your level and also to the level of Anthony Accioly, you are masters really, thank you very much for the help, I apologize for the mistakes, I am new to the site and I will seek to improve my questions and answers.

Browser other questions tagged

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