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

时间:2015-03-06 12:25:17

标签: python list sorting

如何根据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']]

4 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:1)

from operator import itemgetter    
sorted(list01, key=itemgetter(0))

答案 2 :(得分:0)

>>> sorted(list01, key=lambda l: l[0])
[['a', 'b', 'c'], ['a', 'f', 'd'], ['b', 'a', 'd'], ['d', 'e', 'c']]

这是你的意思吗?

答案 3 :(得分:0)

除了将key函数传递给sorted之外(如前面的答案中所示),您还可以在Python2中传递cmp(比较)函数,如下所示:

sorted(list01, cmp=lambda b, a: cmp(b[0], a[0]))

上述表达式的输出与使用key函数的输出相同。

虽然他们已从cmp删除了Python3中的sorted参数,https://docs.python.org/3.3/library/functions.html#sorted,但使用key函数是唯一的选择。

相关问题