python sort嵌套列表
时间: 2024-09-07 17:00:24 浏览: 60
在Python中,如果你有一个嵌套列表(list of lists),也就是包含其他列表的列表,你可以使用`sort()`函数对其进行排序,但是直接对整个嵌套列表进行排序可能会有些复杂。因为`sort()`默认会比较每个元素,而不是整组列表。这里有几个选项:
1. **仅对内部列表排序**:如果你想保持外部列表不变,只对内部列表排序,可以先遍历并单独处理每层。例如,假设你有二维列表`lst`,你可以这样做:
```python
lst = [[4, 2], [1, 5], [3, 6]]
sorted_lst = sorted(lst, key=lambda x: x[0]) # 按照第一个元素排序
# 或者对每一项进行排序
for i in range(len(lst)):
lst[i] = sorted(lst[i])
```
2. **深度排序**:如果你想要按照整个嵌套结构的某种方式进行排序(比如整个列表都是按照某个属性排序),你需要提供自定义的排序函数`key`,该函数需要接受一个嵌套列表作为输入,并返回一个用于比较的值。例如,假设你想按列排序,可以这样写:
```python
lst = [[4, 2], [1, 5], [3, 6]]
sorted_lst = sorted(lst, key=lambda inner_list: inner_list[1])
# 如果你想根据所有列的总和排序
def sum_key(inner_list):
return sum(inner_list)
sorted_lst = sorted(lst, key=sum_key)
```
阅读全文
相关推荐


















