[英]How to check a condition on a list (or array) and then sort the elements based on that condition in Python
[英]How to sort list in python with different indexes based on condition?
我是 python 的新手,我想按第一个索引按非递减顺序对 python 中的列表列表进行排序,但如果第一个索引包含相等的值,则按第二个索引按降序排序
例如[[3,3],[3,2],[1,3]]
output [[1,3],[3,3][3,2]]
ex2[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
输出[[4, 4], [5, 2],[5, 0], [6, 1], [7, 1],[7, 0]]
在 c++ 我用这个 function 作为钥匙
static bool lessThan(vector<int> &l , vector<int> &r)
{
if (r[0] == l[0])
return l[1]>r[1];
return l[0]<r[0];
}
但是在 python 键 function 有不同的行为
由于您只是对数字进行排序,因此您可以走捷径,只取元组中第二个元素的负数:
l = [[3,3],[3,2],[1,3], [3,5], [3,0], [3, -1]]
sorted(l, key=lambda x: (x[0], -x[1]))
# [[1, 3], [3, 5], [3, 3], [3, 2], [3, 0], [3, -1]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.