简体   繁体   English

如何对列表列表中的每个列表进行排序

[英]How to sort each list in a list of lists

How can I sort the lists in the following nested list?如何对以下嵌套列表中的列表进行排序? Function sort works only on normal lists. Function sort仅适用于普通列表。

lst = [[123,3,12],[89,14,2],[901,4,67]]

Expected result:预期结果:

[[3,12,123],[2,14,89],[4,67,901]] 

This is a very straightforward way to do it without any packages (list comprehension)这是一种非常简单的方法,无需任何包(列表理解)

lst_sort = [sorted(item) for item in lst]

try this:尝试这个:

lst = [[123,3,12],[89,14,2],[901,4,67]]

for element in lst:
    element.sort()

print(lst)

Loop through each item and sort separately.循环遍历每个项目并分别排序。

Here's a functional way to achieve this using map() with sorted() as:这是使用map()sorted()实现此目的的一种功能方法:

>>> lst = [[123,3,12],[89,14,2],[901,4,67]]

>>> list(map(sorted, lst))
[[3, 12, 123], [2, 14, 89], [4, 67, 901]]

To know more about these functions, refer:要了解有关这些功能的更多信息,请参阅:

Just sort each sub list independently:只需对每个子列表进行独立排序:

lst = [[123,3,12],[89,14,2],[901,4,67]]
lst = [sorted(sub) for sub in lst]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM