写在前面:
在处理排序任务时候,有时候需要对表格进行排序,比如第一列升序,第二列降序。。
解决方案:
思路一:
用Python的sort特性进行:
匿名函数中的x代表两个元素的列表,
如果某一列i降序,就在x[i]加负号
t = [
[1, 3],
[2, 1],
[1, 2],
[3, 1]
]
t.sort(key=lambda x: (x[0], -x[1]))
print(t)
"""
输出:
[[1, 3], [1, 2], [2, 1], [3, 1]]
"""
思路2:
将待比较元素分装到一个可比较类里,然后再排序
from operator import gt, lt
class SSK:
def __init__(self, k):
self.c1 = k[0]
self.c2 = k[1]
def __gt__(self, other):
if other.c1 == self.c1:
return not gt(self.c2, other.c2)
else:
return gt(self.c1, other.c1)
t = [
[1, 3],
[2, 1],
[1, 2],
[3, 1]
]
tt = list(map(lambda x: SSK(x), t))
tt.sort()
print(list(map(lambda x: [x.c1, x.c2], tt)))