Return tuple with smallest y value from list of tuples

前端 未结 1 1058
别跟我提以往
别跟我提以往 2021-02-20 08:14

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 la

1条回答
  •  佛祖请我去吃肉
    2021-02-20 09:15

    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)
    

    0 讨论(0)
提交回复
热议问题