简体   繁体   English

对列表中的列表列表进行排序

[英]Sorting a list of lists in a list

Say I have a list inside a list, that is contained inside a list. 假设我在列表中有一个列表,它包含在列表中。 For example: 例如:

foo = [[[2, 2, 2], [1, 1, 1], [3, 3, 3]], [[2, 2, 2], [1, 1, 1], [3, 3, 3]]]

And I wanted to sort it in order: 我想按顺序排序:

foo = [[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[1, 1, 1], [2, 2, 2], [3, 3, 3]]]

I could use [sorted(i) for i in foo] to achieve this. 我可以使用[sorted(i) for i in foo]来实现这一点。 However is there some way to sort this list without list comprehension (or creating a new list)? 但是有没有办法在没有列表理解(或创建新列表)的情况下对此列表进行排序?

The values inside the lists themselves will change but do not need to be sorted. 列表内部的值将会更改,但不需要进行排序。

Everything I have tried just boils down to the same method as above. 我尝试过的所有东西都归结为与上面相同的方法。

If you want to avoid creating a new list, then just iterate over the lists and call .sort() 如果你想避免创建一个新列表,那么只需遍历列表并调用.sort()

>>> foo = [[[2, 2, 2], [1, 1, 1], [3, 3, 3]], [[2, 2, 2], [1, 1, 1], [3, 3, 3]]]

for i in foo:
    i.sort()

>>> foo                                                                         
[[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[1, 1, 1], [2, 2, 2], [3, 3, 3]]]

If you don't mind creating a new list, how about using map function: 如果您不介意创建新列表,请使用map函数:

In [1]: foo = [[[2, 2, 2], [1, 1, 1], [3, 3, 3]], [[2, 2, 2], [1, 1, 1], [3, 3, 3]]]

In [2]: list(map(sorted, foo))
Out[2]: [[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[1, 1, 1], [2, 2, 2], [3, 3, 3]]]

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

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