python多重邏輯排序


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]倒排。 這里面是有邏輯順序的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM