>>> from operator import itemgetter
>>> ul = [(10,2),(9,4),(10,3),(10,4),(9,1),(9,3)]
>>> ol = sorted(ul, key=itemgetter(0,1), reverse=True)
>>> ol
[(10, 4), (10, 3), (10, 2), (9, 4), (9, 3), (9, 1)]
我想要的是在第二个键上排序reverse = False。换句话说,我希望结果是:
[(10, 2), (10, 3), (10, 4), (9, 1), (9, 3), (9, 4)]
我该怎么做?
答案 0 :(得分:5)
对于排序数字,您可以使用否定排序键:
sorted(ul, key=lambda x: (-x[0], x[1]))
或者,如果您有非数字数据,则可以进行两遍排序(首先按最低有效键排序):
ol = sorted(ul, key=lambda x: x[1])
ol = sorted(ol, key=lambda x: x[0], reverse=True)