Skip to main content
 首页 » 编程设计

python之如何在 Python3 中使用两个条件对对象进行排序

2025年05月04日14sky-heaven

  • 字母表示列表中的对象。
  • 每个字母表都有一个中心坐标 (x,y)。
  • 数字代表它在列表中的索引。

我想按 [A,​​ B, C, D] 的顺序对项目进行排序。所以……

if abs(A.y - B.y) < threshold: 
    # sort by x coordinate 
else: 
    # sort by y coordinate 

我可以通过手动检查对象并直接交换它们的位置来做到这一点。

但是我如何使用 Python3 sorted(key=) 函数做到这一点?

请您参考如下方法:

写一个比较函数,然后用functools.cmp_to_key把它转换成一个key函数:

# Given a threshold, return a function suitable for 
# use by old cmp argument 
def comparator(threshold): 
    def compare(A, B): 
        if abs(A.y - B.y) < threshold: 
            return cmp(A.x, B.x) 
        else: 
            return cmp(A.y, B.y) 
    return compare 
 
from functools import cmp_to_key 
my_cmp = comparator(0.6)  # Or whatever threshold you need 
sorted_list = sorted(my_list, key=cmp_to_key(my_cmp))