以Python排序打破平局 [英] Breaking ties in Python sort

查看:53
本文介绍了以Python排序打破平局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个listtuple s,每个元组包含两个整数.我需要根据每个元组中整数的差异对列表进行排序(以相反的顺序),但要与较大的第一个整数断开联系.

I have a list of tuples, each tuple contains two integers. I need to sort the the list (in reverse order) according to the difference of the integers in each tuple, but break ties with the larger first integer.

示例

对于[(5, 6), (4, 1), (6, 7)],我们应该得到[(4, 1), (6, 7), (5, 6)].

我的方式

我已经通过制作一个dictionary来解决它,其中包含的差异为key而元组为value.但是整个过程有点笨拙.

I have already solved it by making a dictionary that contains the difference as the key and the tuple as the value. But the whole thing is a bit clumsy.

有什么更好的方法?

推荐答案

sorted()使用key函数并返回一个元组;值将按字典顺序排序:

Use a key function to sorted() and return a tuple; values will be sorted lexicographically:

sorted(yourlst, key=lambda t: (abs(t[0] - t[1])), t[0]), reverse=True)

我在这里使用abs()来计算差值,而不管两个整数中的哪个较大.

I'm using abs() here to calculate a difference, regardless of which of the two integers is larger.

对于示例输入,键产生(1, 5)(3, 4)(1, 6)

For your sample input, the key produces (1, 5), (3, 4) and (1, 6); in reverse order that puts (1, 6) (for the (6, 7) tuple) before (1, 5) (corresponding with (5, 6)).

演示:

>>> yourlst = [(5, 6), (4, 1), (6, 7)]
>>> sorted(yourlst, key=lambda t: (abs(t[0] - t[1]), t[0]), reverse=True)
[(4, 1), (6, 7), (5, 6)]

这篇关于以Python排序打破平局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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