You should consider transforming the list of lists into a list of dictionaries if possible, as you say @MLStud, these operations would be much simpler and more efficient, especially using operator.itemgetter
and min
/ max
, only by way of idea:
lista = [{'Metros': 405, "Nombre": 'edificio A', "Direccion": 'San Lorenzo'},
{'Metros': 1843, "Nombre": 'edificio B', "Direccion": 'Eusebio Blanco'},
{'Metros': 3067, "Nombre": 'edificio C', "Direccion": 'Av. San Martín Sur , Godoy Cruz'},
{'Metros': 2863, "Nombre": 'edificio D', "Direccion": 'Tomás Godoy Cruz'}]
from operator import itemgetter
minimo = min(lista, key=itemgetter("Metros"))
>>> minimo
{'Metros': 405, "Nombre": 'edificio A', "Direccion": 'San Lorenzo'}
You can build the dictionary and add it to the list with:
lista.append({'Metros': metros, 'Nombre': nombre, 'Direccion': direccion})
If you can not do this, you can also use the built-in min
and its argument key
but passing it a function that is responsible for taking each sublist, take the first item, get the number by applying str.rsplit
and pass it to float
or int
(so as not to carry out a lexicographical ordering). This is significantly more inefficient than using a dictionary since it requires a function call in pure Python, called%% co and casting to scale and two indexing operations on lists (whereas the previous example is mostly done using C code) compiled directly):
minimo = min(lista, key=lambda item: float(item[0].rsplit(" ", maxsplit=1)[-1]))
>>> minimo
['Metros: 405', 'edificio A', 'San Lorenzo']
Note: str.rsplit
looks for the first space in the chain from right to left and breaks the string there without looking further.