简体   繁体   English

如何在Python中对嵌套列表的外部和内部子列表进行排序?

[英]How to sort the outer and inner sublist of a nested list in Python?

First of all, apologies if this too naive (I am a beginner). 首先,如果这太天真了,我会道歉(我是初学者)。 I have the following type of list of lists, which I would like to first sort by the last member of the inner list in ascending order: 我有以下类型的列表列表,我想首先按内部列表的最后一个成员以升序排序:

data =  [[1, .45, 0], [2, .49, 2], [3, .98, 0], [4, .82, 1], [5, .77, 1], [6, .98, 2] ]

I accomplish this by using : sorted(data,key=operator.itemgetter(2),reverse = True) , which gives me: 我使用以下方法完成此操作: sorted(data,key=operator.itemgetter(2),reverse = True) ,这给我:

[[1, .45, 0], [3, .98, 0],[4, .82, 1], [5, .77, 1], [2, .49, 2], [6, .98, 2]]

Now, I would like to sort within the sub-lists ie first sort the list with its last member as '0' using the middle member as the key, in descending order. 现在,我想在子列表中进行排序,即首先使用中间成员作为关键字,将最后一个成员为'0'的列表进行排序。 Then sort the sub-list with '1' as its last member and so on. 然后,以“ 1”作为最后一个成员对子列表进行排序,依此类推。 Note that number of elements in each sub-list are different and are not know. 请注意,每个子列表中的元素数量都不相同,并且未知。 The final list should look like this: 最终列表应如下所示:

[[3, .98, 0],[1, .45, 0], [4, .82, 1], [5, .77, 1], [6, .98, 2],[2, .49, 2] ]

The list is actually quite huge, therefore I am looking for an efficient implementation. 该列表实际上非常庞大,因此我正在寻找一种有效的实现。 Any guidance would be appreciated ! 任何指导将不胜感激 !

>>> data =  [[1, .45, 0], [2, .49, 2], [3, .98, 0], [4, .82, 1], [5, .77, 1], [6, .98, 2] ]
>>> sorted(data, key=lambda x:(x[2], -x[1]))
[[3, 0.98, 0], [1, 0.45, 0], [4, 0.82, 1], [5, 0.77, 1], [6, 0.98, 2], [2, 0.49, 2]]

You can add extra terms to the lambda as required 您可以根据需要向lambda添加额外的条款

You can pass sorted multiple keys: 您可以传递排序的多个键:

data =  [[1, .45, 0], [2, .49, 2], [3, .98, 0], [4, .82, 1], [5, .77, 1], [6, .98, 2] ]
sorted(data, key=lambda x: (x[2], -x[1]))

[[3, 0.98, 0],
 [1, 0.45, 0],
 [4, 0.82, 1],
 [5, 0.77, 1],
 [6, 0.98, 2],
 [2, 0.49, 2]]

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

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