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