简体   繁体   English

如何使列表列表中的每个列表按升序排序?

[英]How do I make each list in the list of lists sort in ascending order?

I have the following lists: 我有以下列表:

[[1, 5], [3, 7], [4, 2], [7, 8], [6, 3], [2, 5], [4, 1]]

And I am trying to sort them by the first value, after making the list go in ascending order: 在使列表按升序排列后,我尝试按第一个值对它们进行排序:

Desired output: 所需的输出:

[[1, 4], [1, 5], [2, 4], [2, 5], [3, 6], [3, 7], [7, 8]]

However, list.sort() only gives the following: 但是, list.sort()仅给出以下内容:

>>> mylist = [[1, 5], [3, 7], [4, 2], [7, 8], [6, 3], [2, 5], [4, 1]]
>>> mylist.sort()
>>> mylist
[[1, 5], [2, 5], [3, 7], [4, 1], [4, 2], [6, 3], [7, 8]]
>>> 

Of course, I could always loop each list in the list of lists and sort it: 当然,我总是可以循环列表列表中的每个列表并对其进行排序:

>>> mylist
[[1, 5], [2, 5], [3, 7], [4, 1], [4, 2], [6, 3], [7, 8]]
>>> for k in range(len(mylist)):
...     mylist[k] = sorted(mylist[k])
... 
>>> mylist
[[1, 5], [2, 5], [3, 7], [1, 4], [2, 4], [3, 6], [7, 8]]
>>> sorted(mylist)
[[1, 4], [1, 5], [2, 4], [2, 5], [3, 6], [3, 7], [7, 8]]

But is there a one liner to solve this? 但是,有没有一个班轮来解决这个问题?

你可以做:

sorted(sorted(sublist) for sublist in mylist)

This is a little better than your loop: 这比循环更好:

for sublist in mylist:
    sublist.sort()

mylist.sort()

Of course, this changes each sublist in-place . 当然,这会就地更改每个子列表。 Judging by your examples, it looks like that is what you want, but I thought I should mention it just in case. 从您的示例来看,这看起来就是您想要的,但是我认为我应该提一下,以防万一。

Here is a one liner that does the sort in-place 这是一个可以就地进行分类的班轮

>>> mylist = [[1, 5], [3, 7], [4, 2], [7, 8], [6, 3], [2, 5], [4, 1]]
>>> mylist.sort(key=lambda x:x.sort() or x)
>>> mylist
[[1, 4], [1, 5], [2, 4], [2, 5], [3, 6], [3, 7], [7, 8]]

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

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