简体   繁体   English

按每个子列表的第一个元素对列表列表进行排序

[英]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.

相关问题 Python 。 如果第二个元素相等,如何对子列表的元素进行排序 按第一个元素对子列表进行排序 - Python . How to sort elements of sub-list if second elements are equal sort the sub-lists by first element Python代码按该子列表第一个元素的索引访问子列表 - Python code to access sub-List by index of first element of that sub-List 不同子列表项的可能集合,每个子列表有一个元素 - Possible sets of different sub-list items with one element of each sub-list 从嵌套列表中的所有子列表中删除第一个元素 - Removing the first element from all the sub-list in a nested list Python 列表——去重和添加子列表元素 - Python lists -- deduping and adding sub-list element 列表的列表,减去每个子列表中的值并将结果存储在新的子列表中 - A list of lists, substract the values in each sub-list and store the results in new sub-lists 如果第一个元素相同,则添加两个子列表 - Adding two sub-list if the first element is the same 使用功能将唯一标识符附加到输出列表列表中的每个子列表? - Using a function to append a unique identifier to each sub-list within an outputted list of lists? 如何创建具有 3 个元素的子列表,但是如果子列表只有一个元素,则改为创建两个具有 2 个元素的子列表? - How to create sub-lists with 3 elements, but if a sub-list gets a single element then instead create two with 2 elements? 如何从嵌套列表中的每个子列表中提取直到倒数第二个元素? - How do you extract till the second last element from each sub-list in a nested list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM