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

问题描述

[((D,A),0.0),((D,C),0.0),((D,E),0.5)]

我需要将列表排序为:

[((D,E),0.5),((D,A),0.0),((D,C),0.0)]

我已经使用过sorted()函数,并且能够基于值0.5, 0.0进行排序...但是我无法按字母顺序进行排序,因为我需要使用列表按降序对列表进行排序数字,如果数字具有相同的值,则按字母的升序.

I have used the sorted() function and I am able to sort based on values 0.5, 0.0... But I am not able to sort on the alphabetical order as I need the list to be sorted in descending order by the numbers and in ascending order of alphabets if the numbers have same value.

推荐答案

使用元组作为排序键,并在浮点数上带有负号以反转顺序:

Use a tuple as the sort key with a negative on the float to reverse the order:

>>> li=[(('D','A'),0.0),(('D','C'),0.0),(('D','E'),0.5)]
>>> sorted(li, key=lambda t: (-t[-1],t[0]))
[(('D', 'E'), 0.5), (('D', 'A'), 0.0), (('D', 'C'), 0.0)]

如果您不能进行求反(例如对字符串或字母值或非数字值进行求反),则可以利用Python排序函数稳定的事实,并分两步进行排序:

If you cannot do negation (say on a string or letter value or something non numeric) then you can take advantage of the fact that the Python sort function is stable and do the sort in two steps:

>>> li=[(('D','A'),'A'),(('D','C'),'A'),(('D','E'),'C')]
>>> sorted(sorted(li), key=lambda t: t[-1], reverse=True)
[(('D', 'E'), 'C'), (('D', 'A'), 'A'), (('D', 'C'), 'A')]

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

08-20 12:33
查看更多