Python 标准库

sorted

2022-09-23
1
nums = [5, 2, 3, 1, 4]
2
3
# 基本排序
4
sorted(nums)
5
# 返回: [1, 2, 3, 4, 5]
6
7
# 字典排序
8
nums = {1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}
9
sorted(nums)
10
# 返回 [1, 2, 3, 4, 5]
11
sorted(nums.values())
12
# 返回: ['A', 'B', 'B', 'D', 'E']

注:和 nums.sort 区别是前者会对原列表进行修改

对列表、字典和元祖进行排序

1
from operator import itemgetter, attrgetter
2
3
student_tuples = [
4
('john', 'A', 15),
5
('jane', 'B', 12),
6
('dave', 'B', 10),
7
]
8
9
sorted(student_tuples, key=itemgetter(2))
10
# 返回: [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

参考