Return tuple with smallest y value from list of tuples
Asked Answered
S

1

11

I am trying to return a tuple the smallest second index value (y value) from a list of tuples. If there are two tuples with the lowest y value, then select the tuple with the largest x value (i.e first index).

For example, suppose I have the tuple:

x = [(2, 3), (4, 3), (6, 9)]

The the value returned should be (4, 3). (2, 3) is a candidate, as x[0][1] is 3 (same as x[1][1]), however, x[0][0] is smaller than x[1][0].

So far I have tried:

start_point = min(x, key = lambda t: t[1])

However, this only checks the second index, and does not compare two tuples first index if their second index's are equivalent.

Schlemiel answered 9/5, 2016 at 8:10 Comment(1)
You could try something like: min(x, key=lambda t: [t[1], -t[0]])Blackcock
H
18

Include the x value in a tuple returned from the key; this second element in the key will be then used when there is a tie for the y value. To inverse the comparison (from smallest to largest), just negate that value:

min(x, key=lambda t: (t[1], -t[0]))

After all, -4 is smaller than -2.

Demo:

>>> x = [(2, 3), (4, 3), (6, 9)]
>>> min(x, key=lambda t: (t[1], -t[0]))
(4, 3)
Hunchback answered 9/5, 2016 at 8:19 Comment(2)
@ByteCommander: because in a tie the larger x value should be selected, not the smaller.Hunchback
Thank you, works perfectly. And only one line required!Schlemiel

© 2022 - 2024 — McMap. All rights reserved.