如何按反向排序元组,但不反向断开关系? (Python) [英] How can I sort tuples by reverse, yet breaking ties non-reverse? (Python)

查看:146
本文介绍了如何按反向排序元组,但不反向断开关系? (Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个元组列表:

If I have a list of tuples:

results = [('10', 'Mary'), ('9', 'John'), ('10', 'George'), ('9', 'Frank'), ('9', 'Adam')]

如何像在计分板上看到的那样对列表进行排序-这样可以将得分从最大到最小排序,但按名称的字母顺序打破关系?

How can I sort the list as you might see in a scoreboard - such that it will sort the score from biggest to smallest, but break ties alphabetically by name?

因此,排序后,列表应如下所示:

So after the sort, the list should look like:

results = [('10', 'George'), ('10', 'Mary'), ('9', 'Adam'), ('9', 'Frank'), ('9', 'John')]

目前我所能做的只是results.sort(reverse=True),但打破关系也按字母顺序反向...

At the moment all I can do is results.sort(reverse=True), but breaks ties reverse alphabetically too...

任何帮助将不胜感激.谢谢!

Any help would be much appreciated. Thanks!

推荐答案

实现所需目标的最简单方法是使用python排序稳定的事实.这样可以先按字母顺序排序,然后按分数排序:

The simplest way to achieve what you want is to use the fact that python sort is stable. This allows to first sort alphabetically and then by score:

In [11]: results = [(10, 'Mary'), (9, 'John'), (10, 'George'), (9, 'Frank'), (9, 'Adam')]

In [12]: results.sort(key=lambda x: x[1])

In [13]: results.sort(key=lambda x: x[0], reverse=True)

In [14]: results
Out[14]: [(10, 'George'), (10, 'Mary'), (9, 'Adam'), (9, 'Frank'), (9, 'John')]

第一种排序按字母升序排列.第二种按分数排序,降序排列,保持分数相等的元素的相对顺序.

The first sort sorts alphabetically, in ascending order. The second sort sorts by score, in descending order, maintaining the relative order of elements with equal score.

您可以执行此操作以进行更复杂的排序.请记住,您必须先按 secondary 键,然后再按第一个键排序. (如果您有三个键,请先按第三个键排序,然后再按第二个键排序,最后按主键排序.)

You can do this to do even more complex sorts. Just remember that you must first sort by the secondary key, and then by the first key. (If you have three keys, first sort by the third, then by the second, and lastly by the main key).

如果不想两次调用sort,则必须编写一个更复杂的key函数.像这样:

If you don't want to call sort twice you'll have to write a more complex key function. Something like:

In [50]: def key(elem):
    ...:     return elem[0], [-ord(c) for c in elem[1]]

In [51]: sorted(results, key=key, reverse=True)
Out[51]: [(10, 'George'), (10, 'Mary'), (9, 'Adam'), (9, 'Frank'), (9, 'John')]

特别是,每当您按照字典顺序对某些内容(例如字符串,元组,列表等)进行排序时,都可以通过将符号更改为所有元素来反转顺序.

In particular, every time you have something sorted in lexicographic order(such as strings, tuples, lists etc.), you can invert the order by changing the sign to all the elements.

这篇关于如何按反向排序元组,但不反向断开关系? (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆