python sorted()
时间: 2024-01-04 22:19:48 浏览: 92
以下是使用sorted()函数进行排序的示例代码:
1. 对列表进行排序:
```python
num_list = [5,2, 8, 1, 6]
sorted_list = sorted(num_list)
print(sorted_list) # 输出:[1, 2, 5, 6, 8]
```
2. 对元组列表进行排序:
```python
num_list = [("b", 2), ("a", 1), ("c", 5), ("d", 4)]
sorted_list = sorted(num_list)
print(sorted_list) # 输出:[('a', 1), ('b', 2), ('c', 5), ('d', 4)]
```
3. 对字典进行排序:
```python
num_dict = {"b": 2, "a": 1, "c": 5, "d": 4}
sorted_dict = sorted(num_dict.items())
print(sorted_dict) # 输出:[('a', 1), ('b', 2), ('c', 5), ('d', 4)]
```
4. 自定义排序规则:
```python
num_list = [("b", 2), ("a", 1), ("c", 5), ("d", 4)]
sorted_list = sorted(num_list, key=lambda x: x[1], reverse=True)
print(sorted_list) # 输出:[('c', 5), ('d', 4), ('b', 2), ('a', 1)]
```
阅读全文