Python自定义排序

Ste*_*aly 2 python sorting python-3.x

我正在尝试使用Python的sorted函数对列表进行排序.在Python 3中,cmp删除了关键字参数.不幸的是,我似乎无法使用key关键字参数实现我的算法,因为我需要两个对象来比较数据.

示例排序数据

59 59
59 3 1 1
59 4 3 3
61 1
61 10
61 237
61 1 1 1
Run Code Online (Sandbox Code Playgroud)

比较功能

NUM_RE = re.compile("[\d]+")
def compare(x, y):
    # Aggregate our data into integer arrays
    x_result = [int(x) for x in NUM_RE.findall(x)]
    y_result = [int(y) for y in NUM_RE.findall(y)]

    # Return if there is a non-zero difference in the first element
    statement_diff = x_result[0] - y_result[0]
    if statement_diff != 0:
        return statement_diff

    # Return if there is a non-zero difference between the lengths
    length_diff = len(x_result) - len(y_result)
    if length_diff != 0:
        return length_diff

    # len(x_result) == len(y_result)
    # Iterate over each item and return if there is a difference
    for i in range(1, len(x_result)):
        result = x_result[i] - y_result[i]
        if result != 0:
            return result

    # Results are the same
    return 0
Run Code Online (Sandbox Code Playgroud)

排序这些数据的最佳方法是什么?我应该创建一个"包装物"实现了__eq___,__gt__,__lt__等功能,这样我就可以使用默认的排序功能?或者标准Python API中是否包含另一个功能来完成原始行为sorted

Ste*_*sop 5

Python已经有你描述的包装器,它被称为 functools.cmp_to_key