- 字母表示列表中的对象。
- 每个字母表都有一个中心坐标 (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))
我是一名优秀的程序员,十分优秀!