Python - Multistep排序降序

时间:2016-01-12 16:39:14

标签: python sorting tuples

我正在尝试对元组列表进行排序。排序必须经过多个步骤。步骤是:

(1) Sort descending based on second element of tuple
(2) Sort descending based on string length of first element of tuple
(3) Sort ascending lexicographical order

因此,例如,列表:

[('ident', 3), (')', 2), ('(', 2), (';', 2), ('string', 1), ('}', 1), ('char', 1), ('=', 1), ('{', 1)]

应排序为:

[('ident', 3), ('(', 2),  (')', 2), (';', 2), ('string', 1), ('char', 1),  ('=', 1), ('{', 1), ('}', 1)]

我的尝试是:

theList = sorted(theList, key=lambda x: (x[1], len(x[0]), x[0]))

但这并没有产生所需的输出,我想要像:

theList = sorted(theList, key=lambda x: (x[1].descending(), len(x[0]).descending(), x[0].ascending()))

实现此目的的正确语法是什么?

1 个答案:

答案 0 :(得分:1)

这个怎么样?

>>> l = [('ident', 3), (')', 2), ('(', 2), (';', 2), ('string', 1), ('}', 1), ('char', 1), ('=', 1), ('{', 1)]
>>> sorted(l, key=lambda x: (-x[1], -len(x[0]), x[0]))
[('ident', 3), ('(', 2), (')', 2), (';', 2), ('string', 1), ('char', 1), ('=', 1), ('{', 1), ('}', 1)]

修改

从您的预期输出('=', 1), ('{', 1), ('}', 1)这是一个升序的词典顺序,请查看:

>>> c = ['}','=','{']
>>> map(ord, c)
[125, 61, 123]
>>> sorted(c)
['=', '{', '}'] #what you want to get
>>> map(ord, sorted(c))
[61, 123, 125] #Ascending order

如果您希望按降序字典顺序排列,则可以执行以下操作:

>>> sorted(l, key=lambda x: (-x[1], -len(x[0]), -ord(x[0][0])))
[('ident', 3), (';', 2), (')', 2), ('(', 2), ('string', 1), ('char', 1), ('}', 1), ('{', 1), ('=', 1)]