Breaking ties in Python sort

匿名 (未验证) 提交于 2019-12-03 02:21:02

问题:

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.

Example

For [(5, 6), (4, 1), (6, 7)], we should get [(4, 1), (6, 7), (5, 6)].

My way

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.

What is a better way?

回答1:

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) 

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

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)).

Demo:

>>> 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)] 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!