如何在Python中排列嵌套列表的外部和内部子列表? [英] How to sort the outer and inner sublist of a nested list in Python?

查看:154
本文介绍了如何在Python中排列嵌套列表的外部和内部子列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,如果这太天真了,我很抱歉(我是初学者)。
我有以下类型的列表,我想先按内容列表的最后一个成员按升序排序:

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

code> 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]] 

现在,我想在子列表,首先按照降序将中间的成员作为关键,将列表的最后一个成员作为0排序。然后用1作为其最后一个成员排列子列表,依此类推。请注意,每个子列表中的元素数量不同,不知道。最终列表应如下所示:

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

列表实际上相当庞大,因此我正在寻找一个高效的实现。
任何指导将不胜感激!

解决方案

 >>> data = [[1,.45,0],[2,.49,2],[3,.98,0],[4,.82,1],[5,.77,1],[6 ,.98,2]] 
>>>排序(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]]

您可以根据需要向lambda添加额外的术语


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:

[[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 i.e. first sort the list with its last member as '0' using the middle member as the key, in descending order. Then sort the sub-list with '1' as its last member and so on. 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

这篇关于如何在Python中排列嵌套列表的外部和内部子列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆