pick the minimum value out of a list of sublists and display another value in that sublist with the minimum

StackOverflow https://stackoverflow.com/questions/21959282

Frage

Say I have a list:

stuff =  [[5,3,8],[2,4,7],[14,5,9]]

where each sublist is of the form [x,y,z].

I want to find the minimum value of this list for the third entry in the sub lists, i.e. z=7. Then I want to print out the first value of that sublist, x.

ex) The minimum value of z occurs at x = 2.

War es hilfreich?

Lösung

You can use the builtin min function with the key parameter, like this

stuff = [[5,3,8],[2,4,7],[14,5,9]]
print min(stuff, key = lambda x: x[2])[0]   # 2

To make this more readable, you can unpack the values like this

print min(stuff, key = lambda (x, y, z): z)[0]

For each and every element of stuff, the function assigned to key parameter will be invoked. Now, the minimum value will be determined based on the value returned by that function only.

Andere Tipps

You can pass the built-in min function a key to access the third element in each sublist:

Demo

>>> stuff = [[5,3,8],[2,4,7],[14,5,9]]
>>> x, y, z = min(stuff, key=lambda arr: arr[2])
>>> x, y, z
(2, 4, 7)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top