【问题标题】:How to sort a list by the maximum of two axes in python?如何按python中两个轴的最大值对列表进行排序?
【发布时间】:2019-03-17 20:25:27
【问题描述】:

我想按列表中每个元素的第 0 和第 1 索引的最大值对列表进行排序。

例如,如果我有一个这样的列表:

[[2,1,2],
 [0,3,9],
 [1,2,9],
 [1,1,2],
 [3,2,7]]

排序后应该是这样的:

[[0,3,9],
 [3,2,7],
 [2,1,2],
 [1,2,9],
 [1,1,2]]

那么有什么有效的方法来做到这一点?

我更喜欢使用 numpy,但也欢迎使用其他解决方案。

【问题讨论】:

  • 我对你的输出逻辑感到困惑。
  • 我也没有得到排序模式。
  • @dfundako 它取 max(0th index, 1st index) 然后按照那个排序。

标签: python arrays list sorting numpy


【解决方案1】:

只需将sort 与自定义键功能一起使用:

data = [[2,1,2],[0,3,9],[1,2,9],[1,1,2],[3,2,7]]


data.sort(key=lambda x: max(x[0:2]),reverse=True)

【讨论】:

    【解决方案2】:

    取前两列的逐行最大值,argsort,然后反向得到降序。

    您没有指定任何决胜局,因此这与您想要的输出不匹配。换句话说,您的问题没有唯一的解决方案。

    res = A[A[:, :2].max(1).argsort()[::-1]]
    
    array([[3, 2, 7],
           [0, 3, 9],
           [1, 2, 9],
           [2, 1, 2],
           [1, 1, 2]])
    

    【讨论】:

    • 不需要任何决胜局。这就够了。谢谢!
    猜你喜欢
    • 2015-04-14
    • 2014-04-26
    • 2018-03-08
    • 2011-07-09
    • 2012-12-07
    • 1970-01-01
    • 2018-09-20
    相关资源
    最近更新 更多