有以下两种方法可以实现:
方法一:使用zip函数将所有列表合并成一个元组,然后使用sorted函数进行排序,并使用zip函数解压回原来的子列表。
代码示例:
def sort_list_of_lists(lists): zipped = zip(*lists) sorted_zipped = sorted(zipped) sorted_lists = zip(*sorted_zipped) return [list(sublist) for sublist in sorted_lists]
示例输入:
lists = [[1, 2, 3], [3, 2, 1], ['a', 'c', 'b']]
输出结果:
[[1, 2, 3], [1, 2, 3], ['a', 'b', 'c']]
方法二:使用sorted函数的key参数,并传入lambda函数来定义排序规则
代码示例:
def sort_list_of_lists(lists): return sorted(lists, key=lambda x: x[0])
示例输入:
lists = [[1, 2, 3], [3, 2, 1], ['a', 'c', 'b']]
输出结果:
[[1, 2, 3], [3, 2, 1], ['a', 'c', 'b']] -> [[1, 2, 3], [3, 2, 1], ['a', 'b', 'c']]
上一篇:按第一次出现的时间对列表进行排序
下一篇:按第一个索引删除重复元组的列表