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

2023-08-31Python开发问题
1

本文介绍了使用自定义键对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中的元组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10