Return the smallest value - Python

Asked

Viewed 679 times

0

from collections import OrderedDict #Pra poder acessar os elementos igual listas e tuplas.
                              v                 v                 v
lista_aberta = {(1,3): [1,2,3,4], (1,4): [2,3,4,9], (1,5): [3,4,1,7]}

I need to check all the elements and return which has the [3] lowest value, which in this case is (1.3) where its [3] value equals 4.

use a repeating structure to compare values, or have some more direct method to do this?

1 answer

1


I don’t know any "direct method" ready for this, unless you develop it yourself obviously.

In any case, I would use something similar to this, creating a method for reuse and thus using a "direct method". Using the sys.maxsize(for python2 utilize sys.maxint) to ensure that you always take the lowest value since you are using the highest integer value to compare initially and accessing your choice with loop (I used the for to make it clearer what is happening).

import sys

lista_aberta = {(1,3): [1,2,3,4], (1,4): [2,3,4,9], (1,5): [3,4,1,7]}

menor: int = sys.maxsize
objMenor = {}
for key in lista_aberta:
    if lista_aberta[key][3] < menor:
        menor = lista_aberta[key][3]
        objMenor = {key : lista_aberta[key]}

print('Menor valor da lista é: ', menor, 'Obj ->', objMenor)

Browser other questions tagged

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