Python-基于多个排序项的元组排序列表 [英] Python - sorting list of tuples based on multiple sort items

查看:177
本文介绍了Python-基于多个排序项的元组排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我注意到在元组排序列表中发布了许多问题,但是在查看了几篇文章后,我没有看到列表具有这种特殊格式的任何问题.事先道歉,然后提出一个潜在的重复问题,但是我认为这应该很简单.

First, I have noticed that there are many questions posted on sorting lists of tuples, however after looking over a few posts I did not see any of the questions with this particular format for the list. Apologies in advance then for a potential repeat question, however I think this should be simple.

让元组列表为:

my_list = [(('G', 'J', 'I'), 1.0), (('E', 'H', 'F'), 1.0), (('F', 'H', 'G'), 0.8889), (('I', 'K', 'J'), 0.8889), (('H', 'I', 'G'), 0.8889), (('H', 'J', 'I'), 0.875)]

请注意,列表中的每个元组均由1:另一个长度为3的元组(带有3个字母)和2:一个浮点数组成.我的排序目标很简单:1首先按浮点数对元组列表进行排序,2通过按长度为3的元组中的第一个字母进行排序,然后破坏浮点数中的任何联系,3通过以下方式破坏该字母中的任何联系:按长度为3的元组中的第二个字母排序.所需的输出将是:

Note that each tuple in the list consists of 1: another tuple of length 3 with 3 letters, and 2: a floating point number. My sorting objective is simple then: 1st sort the list of tuples by the floating point number, 2nd break any ties in the floating point number by then sorting by the first letter in the length-3 tuple, 3rd break any ties in that letter by sorting by the 2nd letter in the length-3 tuple. Desired output would then be:

sorted_list = [(('E', 'H', 'F'), 1.0), (('G', 'J', 'I'), 1.0), (('F', 'H', 'G'), 0.8889),  (('H', 'I', 'G'), 0.8889), (('I', 'K', 'J'), 0.8889), (('H', 'J', 'I'), 0.875)]

在此特定示例中,虽然在我的较大数据集中确实如此,但没有出现对第二个字母进行排序以打破第一个字母的关系的情况.

in this particular example, sorting on the 2nd letter to break ties on the first letter did not appear, although it does in my larger dataset.

谢谢!

推荐答案

这是一种方法:第一种排序是在浮点数上反向进行的,而关系是通过对内部元组的排序来破坏的:

Here's one way to do it: the first sort is done in reverse on the float, while the ties are broken by sorting on the inner tuple:

srt_lst = sorted(my_list, key=lambda (x, y): (-y, x)) #python 2
print(srt_lst)
# [(('E', 'H', 'F'), 1.0), (('G', 'J', 'I'), 1.0), (('F', 'H', 'G'), 0.8889), (('H', 'I', 'G'), 0.8889), (('I', 'K', 'J'), 0.8889), (('H', 'J', 'I'), 0.875)]

在Python 3中,您必须索引lambda的单个参数才能访问项目并将其用于排序:

In Python 3, you'll have to index the lambda's single parameter to access the items and use them for sorting:

srt_lst = sorted(my_list, key=lambda tup: (-tup[1], tup[0]))

这篇关于Python-基于多个排序项的元组排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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