[英]Sorting list of lists by the first element of each sub-list
How to sort a list of lists according to the first element of each list?如何根据每个列表的第一个元素对列表列表进行排序?
For example, giving this unsorted list:例如,给出这个未排序的列表:
[[1,4,7],[3,6,9],[2,59,8]]
The sorted result should be:排序结果应该是:
[[1,4,7],[2,59,8],[3,6,9]]
Use sorted function along with passing anonymous function as value to the key argument.使用排序函数以及将匿名函数作为值传递给 key 参数。
key=lambda x: x[0]
will do sorting according to the first element in each sublist. key=lambda x: x[0]
将根据每个子列表中的第一个元素进行排序。
>>> lis = [[1,4,7],[3,6,9],[2,59,8]]
>>> sorted(lis, key=lambda x: x[0])
[[1, 4, 7], [2, 59, 8], [3, 6, 9]]
If you're sorting by first element of nested list, you can simply use list.sort()
method.如果您按嵌套列表的第一个元素排序,则可以简单地使用
list.sort()
方法。
>>> lis = [[1,4,7],[3,6,9],[2,59,8]]
>>> lis.sort()
>>> lis
[[1, 4, 7], [2, 59, 8], [3, 6, 9]]
If you want to do a reverse sort, you can use lis.reverse()
after lis.sort()
如果要进行反向排序,可以在
lis.reverse()
之后使用lis.sort()
>>> lis.reverse()
>>> lis
[[3, 6, 9], [2, 59, 8], [1, 4, 7]]
li = [[1,4,7],[3,6,9],[2,59,8]]
li.sort(key=lambda x: int(x[0]))
This will sort in place changing the original list though.不过,这将就地排序更改原始列表。 If you want to keep the original list, it is better to use:
如果要保留原始列表,最好使用:
sorted(li, key = lambda x: int(x[0]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.