Skip to main content
 首页 » 编程设计

python之基于特定元素对列表进行排序之Python

2024年10月25日10leader

如何在 Python 中根据列表的第一个元素对列表列表进行排序?

>>> list01 = (['a','b','c'],['b','a','d'],['d','e','c'],['a','f','d']) 
>>> map(sorted, list01) 
[['a', 'b', 'c'], ['a', 'b', 'd'], ['c', 'd', 'e'], ['a', 'd', 'f']] 
>>> sorted(map(sorted, list01)) 
[['a', 'b', 'c'], ['a', 'b', 'd'], ['a', 'd', 'f'], ['c', 'd', 'e']] 

请您参考如下方法:

Python 的 sorted() 可以接收一个函数来排序。 如果要按每个子列表中的第一个元素排序,可以使用以下命令:

>>> lst = [[2, 3], [1, 2]] 
>>> sorted(lst, key=lambda x: x[0]) 
[[1, 2], [2, 3]] 

有关 sorted() 的更多信息,请参阅 official docs .