You only need one call to sort
, because Python automatically sorts tuples lexicographically. That is, if you ask Python to compare two tuples it will order them by their first element, except if those compare equal in which case it will order them by their second element, except if those compare equal in which case...
You want to sort the list of elements by minus their length and then alphabetically, so you want the key of a string s
to be the tuple (-len(s), s)
. Hence:
>>> l = ['aa','aaa','aaaa','b','bb','z','ccc']
>>> sort_key = lambda s: (-len(s), s)
>>> l.sort(key=sort_key)
>>> l
['aaaa', 'aaa', 'ccc', 'aa', 'bb', 'b', 'z']
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…