如何通过反向对元组进行排序,但打破非反向关系?(Python) [英] How can I sort tuples by reverse, yet breaking ties non-reverse? (Python)

查看:29
本文介绍了如何通过反向对元组进行排序,但打破非反向关系?(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 sort 是稳定的这一事实.这允许先按字母顺序排序,然后按分数排序:

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天全站免登陆