使用自定义键在python中对元组进行排序(sorting tuples in python with a custom key)
嗨:我试图以自定义的方式对元组列表进行排序:
例如:lt = [(2,4), (4,5), (5,2)]
必须排序:
lt = [(5,2), (2,4), (4,5)]
规则:
* b元组大于一个元组,如果a [1] == b [0]
*如果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 = [(2, 4), (4, 5), (5, 2)]
我究竟做错了什么?
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?
原文:https://stackoverflow.com/questions/4554115
更新时间:2023-09-06 07:09