使用自定义键在python中对元组进行排序 [英] sorting tuples in python with a custom key

查看:134
本文介绍了使用自定义键在python中对元组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

必须排序:

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

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

,则元组大于b元组

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

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

但对列表进行排序:

lt.sort(tcmp)

lt show me:

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 .

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.

这篇关于使用自定义键在python中对元组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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