Skip to content

Commit 2c8a81b

Browse files
committed
sort 嵌套排序技巧
1 parent 4eb9fe7 commit 2c8a81b

File tree

1 file changed

+2
-1
lines changed
  • docs/19_python内置常用算法和数据结构

1 file changed

+2
-1
lines changed

docs/19_python内置常用算法和数据结构/builtins.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -101,10 +101,11 @@ class Solution:
101101
# python list 技巧
102102

103103
```py
104-
# 排序嵌套 list
104+
# 排序嵌套 list,比如元素值是一个 tuple 或者 list
105105
l = [('a', 1), ('c', 2), ('b',3)]
106106
sorted(l, key=lambda p:p[0]) # 根据第1个值排序,[('a', 1), ('b', 3), ('c', 2)]
107107
sorted(l, key=lambda p:p[1]) # 根据第2个值排序,[('a', 1), ('c', 2), ('b', 3)]
108+
sorted(l, key=lambda p:(-p[0], p[1])) # 先根据第一个倒排,如果相等再根据第二个正排序
108109

109110
# 同时获取最大值的下标和值
110111
l = [1,2,5,4,3]

0 commit comments

Comments
 (0)