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

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

问题描述

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

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)