简体   繁体   English

按优先级在python中的列排序矩阵

[英]Order a matrix by columns with priority in python

i have the following matrix: 我有以下矩阵:

catch = [['fc', 2, 12, 2], 
 ['abcd', 1, 2, 0], 
 ['ab', 1, 0, 0], 
 ['cf', 1, 13, 0], 
 ['fc', 1, 14, 0], 
 ['f', 1, 11, 0]] 

and i want this matrix to be ordered by the fourth columns firstly (index 3), when the values of the fourth column are equals, order by the lenght of the string in the first column (index 0). 并且我希望这个矩阵首先按第四列排序(索引3),当第四列的值等于时,按第一列(索引0)中字符串的长度排序。

i just used 我刚刚用过

catch.sort(key=lambda x: x[3]) 

to sort the matrix by fourth column 按第四列排序矩阵

Just make your key function return a tuple: 只需让你的键功能返回一个元组:

catch.sort(key=lambda x: (x[3], len(x[0]))) 

This works because two tuples are compared item by item, starting from index 0, stopping as soon as a difference is found (or one of the tuples runs out of items, in which case the longer tuple is considered to be larger, but that won't be relevant here, since our tuples all have a length of 2). 这是有效的,因为从索引0开始逐项比较两个元组,一旦找到差异就停止(或者其中一个元组用完项目,在这种情况下,更长的元组被认为更大,但赢了这里不相关,因为我们的元组都有2的长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM