I have some tuples: (0,1,2)
, (3,4,4)
, (2,2,2)
and I would like to find the minimum of the the zero index such that the second index equals 2
. I have tried this using the min
built-in function but it is giving me a syntax error.
min(data, key=lambda x: x if x[2] == 2)
CodePudding user response:
Don't use the key parameter. If you want to ignore certain elements in finding the minimum, use filter()
instead:
data = [(0,1,2), (3,4,4), (2,2,2)]
print(min(filter(lambda x: x[2] == 2, data)))
This outputs:
(0, 1, 2)
CodePudding user response:
You're almost there. You should pass a generator expression to min
which filters the list accordingly.
>>> data = [(0,1,2), (3,4,4), (2,2,2)]
>>> min((x for x in data if x[2] == 2), key=lambda x: x[0])
(0, 1, 2)
Of course, the default behavior of min
on a list of tuples of numbers like this means that explicitly keying min
on the first element of the tuple is not necessary, though it does possibly make the intent of the code more explicit.
min(x for x in data if x[2] == 2)