2016-09-26 120 views
-1
[((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排序......但我不能夠按字母順序排序,因爲如果數字具有相同的值,我需要按照數字降序排列列表並按字母升序排序。

+1

'sorted(li,key = lambda t:(-t [-1],t [0]))' – dawg

回答

2

使用一個元組的排序鍵帶有負上浮子顛倒順序:

>>> 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的排序功能是穩定的,並做排序分爲兩步:

>>> 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')] 
+0

Nice and Nifty code !!!!非常感謝@dawg –

+0

關於如何在Python中排序,有一個很棒的[概述](https://wiki.python.org/moin/HowTo/Sorting)。 – dawg

1

同樣,你可以用一個迭代提供sorted那就是另一sort結果:

>>> from operator import itemgetter 
>>> t = [(('D','A'),0.0),(('D','C'),0.0),(('D','E'),0.5)] 
>>> sorted(sorted(t), key=itemgetter(1), reverse=True) 
[(('D', 'E'), 0.5), (('D', 'A'), 0.0), (('D', 'C'), 0.0)]