python 排序函数
时间: 2023-11-17 10:45:17 浏览: 30
Python 提供了多种排序函数,常用的有 `sorted()` 和 `list.sort()`。下面是它们的介绍:
1. `sorted()` 是内置函数,用于对可迭代对象进行排序,并返回一个新的已排序的列表。它接受一个可迭代对象作为参数,并可以通过 `key` 参数指定排序的依据。例如:
```python
numbers = [3, 1, 4, 2, 5]
sorted_numbers = sorted(numbers) # 默认升序排序
print(sorted_numbers) # 输出: [1, 2, 3, 4, 5]
```
2. `list.sort()` 是列表对象的方法,用于对列表进行原地排序(即在原列表上进行修改,不返回新列表)。它也可以接受 `key` 参数来指定排序的依据。例如:
```python
numbers = [3, 1, 4, 2, 5]
numbers.sort() # 默认升序排序
print(numbers) # 输出: [1, 2, 3, 4, 5]
```
这两个函数都支持通过 `reverse` 参数进行降序排序。例如:
```python
numbers = [3, 1, 4, 2, 5]
sorted_numbers = sorted(numbers, reverse=True) # 降序排序
print(sorted_numbers) # 输出: [5, 4, 3, 2, 1]
numbers = [3, 1, 4, 2, 5]
numbers.sort(reverse=True) # 降序排序
print(numbers) # 输出: [5, 4, 3, 2, 1]
```
希望能帮到你!如有更多问题,请继续提问。