如何在 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 .
关于python - 基于特定元素对列表进行排序 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28898748/