【问题标题】:Python: Get max pair in a list of pairs with min yPython:在具有最小y的对列表中获取最大对
【发布时间】:2011-07-04 08:17:58
【问题描述】:

我如何在具有最小 y 的对列表中获得最大对?

我得到了这份清单:

L =[[1,3],[2,5],[-4,0],[2,1],[0,9]]

使用 max(L) 我得到 [2,5],但我想要 [2,1]。

【问题讨论】:

    标签: python list max min


    【解决方案1】:
    max(L, key=lambda item: (item[0], -item[1]))
    

    输出:

    [2, 1]
    

    【讨论】:

    • 我喜欢这个解决方案。也可以使用元组展开max(L, key=lambda (x, y): (x, -y))
    【解决方案2】:
    import operator
    
    get_y= operator.itemgetter(1)
    min(L, key=get_y)[0]
    

    找到最小y的坐标,检索x

    如果你不喜欢operator.itemgetter,请:

    min(L, key=lambda c: c[1])[0]
    

    【讨论】:

      【解决方案3】:

      您的请求有点神秘,但我认为这就是您想要的:

      x, y = zip(*L)
      maxPairs = [L[i] for i,a in enumerate(x) if a == max(x)]
      returnPair = sorted(maxPairs)[0]
      

      【讨论】:

      • singularity 的解决方案是您应该使用的解决方案。
      猜你喜欢
      • 2017-09-20
      • 2010-11-30
      • 2015-08-11
      • 1970-01-01
      • 2023-02-17
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多