Python sorted() 函数用于对可迭代对象排序,返回新列表,不修改原对象。
语法
sorted(iterable, key=None, reverse=False)参数
| 参数 | 说明 |
|---|---|
iterable | 要排序的可迭代对象 |
key | 可选,指定排序依据(函数) |
reverse | 可选,True 为降序,默认 False |
返回值
返回新的排序后列表,不修改原对象。
示例
nums = [3, 1, 2]
print(sorted(nums)) # [1, 2, 3]
print(nums) # [3, 1, 2],原列表没变
print(sorted(nums, reverse=True)) # [3, 2, 1]
words = ["banana", "apple", "cherry"]
print(sorted(words)) # 按字母序
print(sorted(words, key=len)) # 按长度排
students = [("Tom", 88), ("Ann", 95), ("Bob", 72)]
print(sorted(students, key=lambda s: s[1], reverse=True)) # 按成绩降序输出:
[1, 2, 3]
[3, 1, 2]
[3, 2, 1]
['apple', 'banana', 'cherry']
['apple', 'Bob', 'Tom']
[('Ann', 95), ('Tom', 88), ('Bob', 72)]注意事项
sorted 返回新列表(不改原对象),list.sort() 是原地排序(返回 None)。key 指定排序依据,非常常用。