python有自帶的排序sorted函數,而且用reverse =True or False,來控制降序還是升序。但是如果有多個條件需要排序應該如何辦呢?
L = [(12, 12), (34, 13), (32, 15), (12, 24), (32, 11), (32, 11)] L.sort(key=lambda x: (x[0], -x[1]),reverse=True) print(L) 結果: [(34, 13), (32, 11), (32, 11), (32, 15), (12, 12), (12, 24)] 排序邏輯是:看到先按照tuple[1]進行倒排,如果tuple[1]相等就按照tuple[2]正排
L = [(12, 12), (34, 13), (32, 15), (12, 24), (32, 11), (32, 11)]
L.sort(key=lambda x: (x[0], x[1]),reverse=True)
print(L)
結果: [(34, 13), (32, 15), (32, 11), (32, 11), (12, 24), (12, 12)]
去掉了-之后,可以看到先按照tuple[1]進行倒排,如果tuple[1]相等就按照tuple[2]倒排。 這里面是有邏輯順序的。
