使用自定义键对python中的元组进行排序

2022-01-20 00:00:00 python tuples sorting

问题描述

嗨:我正在尝试以自定义方式对元组列表进行排序:
例如:

lt = [(2,4), (4,5), (5,2)]

必须排序:

lt = [(5,2), (2,4), (4,5)]

规则:
* 如果 a[1] == b[0]
,则 b 元组大于元组* 如果 a[0] == b[1] 则 a 元组大于 b 元组

我已经实现了一个这样的 cmp 函数:

def tcmp(a, b):如果 a[1] == b[0]:返回 -1elif a[0] == b[1]:返回 1别的:返回 0

但对列表进行排序:

lt.sort(tcmp)

给我看:

lt = [(2, 4), (4, 5), (5, 2)]

我做错了什么?

解决方案

我不确定您的比较函数在数学意义上是否有效,即传递性.给定 a, b, c 一个比较函数,表示 a >bb >c 意味着 a >c.排序过程依赖于这个属性.

更不用说根据你的规则,对于 a = [1, 2]b = [2, 1] 你有两个 a[1] == b[0]a[0] == b[1] 这意味着 a 既大于也小于 b.p>

Hi: I'm trying to sort a list of tuples in a custom way:
For example:

lt = [(2,4), (4,5), (5,2)]

must be sorted:

lt = [(5,2), (2,4), (4,5)]

Rules:
* b tuple is greater than a tuple if a[1] == b[0]
* a tuple is greater than b tuple if a[0] == b[1]

I've implemented a cmp function like this:

def tcmp(a, b):
    if a[1] == b[0]:
       return -1
    elif a[0] == b[1]:
       return 1
    else:
       return 0

but sorting the list:

lt.sort(tcmp)

lt show me:

lt = [(2, 4), (4, 5), (5, 2)]

What am I doing wrong?

解决方案

I'm not sure your comparison function is a valid one in a mathematical sense, i.e. transitive. Given a, b, c a comparison function saying that a > b and b > c implies that a > c. Sorting procedures rely on this property.

Not to mention that by your rules, for a = [1, 2] and b = [2, 1] you have both a[1] == b[0] and a[0] == b[1] which means that a is both greater and smaller than b.

相关文章