I'm putting together a list
lista.append(['{}{}'.format('Metros: ', metros),nombre,direccion])
and the output is:
[['Metros: 405', 'edificio A', 'San Lorenzo'], ['Metros: 1843', 'edificio B', 'Eusebio Blanco'], ['Metros: 3067', 'edificio C', 'Av. San Martín Sur , Godoy Cruz'], ['Metros: 2863', 'edificio D', 'Tomás Godoy Cruz']]
How can I obtain from the list the minimum value of Meters.
In this example it should return
['Meters: 405', 'building A', 'San Lorenzo']
You should consider transforming the list of lists into a list of dictionaries if possible as @MLStud tells you, these operations would be much simpler and more efficient especially using
operator.itemgetter
andmin
/max
, just as an idea:You can build the dictionary and add it to the list with:
If you can't do this, you can still use the built-in
min
and its argumentkey
but passing it a function that takes care of taking each sublist, taking the first item, getting the number by applying itstr.rsplit
and passing it tofloat
orint
(so as not to carry out a lexicographic ordering ). This is significantly more inefficient than using a dictionary since it requires a pure Python function call,str.rsplit
a scalar call and casting, and two indexing operations on lists (whereas the above example is mostly done via directly compiled C code). :With that it should work
Following on from Martin's answer, I can think of something to optimize the code. Instead of creating a variable with a very low number and overriding it if it hasn't already been, you could create that variable with a very high number, which you'll never reach, and go from there comparing it to the various numbers.
I think that would be enough c:
A very compact way to solve it could be:
Detail :
[(e,float(e[0].split()[1])) for e in lista]
we build a new list of tuples that will contain the original element together with the meters converted to afloat
. Withsplit()
we separate the first element of each list (the meters) by the space since we are only interested in the number.min()
on the previous list, indicating on which index of the tuples it will be applied:key = lambda x: x[1]