gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:04:58 24 4
gpt4 key购买 nike

Alphabet Data List

  • 字母表示列表中的对象。
  • 每个字母表都有一个中心坐标 (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))

关于python - 如何在 Python3 中使用两个条件对对象进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32824703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com