python排序代码
时间: 2023-12-08 14:36:30 浏览: 30
以下是Python中常用的5种列表排序方法:
1. 使用sorted()函数进行排序
```python
list1 = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_list1 = sorted(list1)
print(sorted_list1) # 输出:[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```
2. 使用sort()方法进行排序
```python
list2 = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
list2.sort()
print(list2) # 输出:[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```
3. 使用reverse参数进行降序排序
```python
list3 = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_list3 = sorted(list3, reverse=True)
print(sorted_list3) # 输出:[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
```
4. 使用key参数进行自定义排序
```python
list4 = ['apple', 'banana', 'orange', 'pear']
sorted_list4 = sorted(list4, key=len)
print(sorted_list4) # 输出:['pear', 'apple', 'banana', 'orange']
```
5. 使用lambda表达式进行自定义排序
```python
list5 = ['apple', 'banana', 'orange', 'pear']
sorted_list5 = sorted(list5, key=lambda x: x[1])
print(sorted_list5) # 输出:['banana', 'pear', 'apple', 'orange']
```