Python数据排序代码
时间: 2023-12-25 13:29:30 浏览: 32
以下是Python中常用的5种列表排序方法的示例代码:
1. 使用sorted()函数进行排序:
```python
list1 = [3, 1, 5, 2, 4]
sorted_list = sorted(list1)
print(sorted_list) # 输出:[1, 2, 3, 4, 5]
```
2. 使用sort()方法进行原地排序:
```python
list2 = [3, 1, 5, 2, 4]
list2.sort()
print(list2) # 输出:[1, 2, 3, 4, 5]
```
3. 使用reverse参数进行降序排序:
```python
list3 = [3, 1, 5, 2, 4]
sorted_list = sorted(list3, reverse=True)
print(sorted_list) # 输出:[5, 4, 3, 2, 1]
```
4. 使用key参数进行自定义排序:
```python
list4 = ['apple', 'banana', 'cherry', 'date']
sorted_list = sorted(list4, key=len)
print(sorted_list) # 输出:['date', 'apple', 'banana', 'cherry']
```
5. 使用lambda函数进行自定义排序:
```python
list5 = ['apple', 'banana', 'cherry', 'date']
sorted_list = sorted(list5, key=lambda x: x[1])
print(sorted_list) # 输出:['banana', 'cherry', 'apple', 'date']
```