如何修复“ TypeError:sort()的无效关键字参数”

2 python sorting python-3.x

使用该compare_points功能订购二维点列表。

我不明白如何将compare_points函数传递给sort()方法。

def compare_points( p, q ):
    if p[0] < q[0] or (p[0] == q[0] and p[1] < q[1]):
        return -1
    elif p[0] > q[0] or (p[0] == q[0] and p[1] > q[1]):
        return 1
    else:
        return 0

#print(compare_points( [1,3], [5,6])) # outputs -1
#print(compare_points( [1,3], [1,6])) # ouputs -1
#print(compare_points( [1,3], [1,3])) # outputs 0
#print(compare_points( [1,3], [0,3])) # outputs 1


L = [ [5,8], [5,2], [12, 3], [1,3], [10,2], [12,1], [12,3] ]
L.sort(cmp=compare_points)
print(L)
Run Code Online (Sandbox Code Playgroud)

实际结果:

L.sort(cmp=compare_points)
builtins.TypeError: 'cmp' is an invalid keyword argument for sort()
Run Code Online (Sandbox Code Playgroud)

预期成绩:

L = [ [1,3], [5,2], [5,8], [10,2], [12,1], [12,3], [12,3] ]
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 5

实际上,这里根本不需要指定键,因为您在此处定义的基本上只是字典顺序,这是在Python中对列表进行排序的标准方式。

因此,您可以在不指定键的情况下进行排序,例如:

>>> L = [ [5,8], [5,2], [12, 3], [1,3], [10,2], [12,1], [12,3] ]
>>> L.sort()
>>> L
[[1, 3], [5, 2], [5, 8], [10, 2], [12, 1], [12, 3], [12, 3]]
Run Code Online (Sandbox Code Playgroud)

在,.sort(..)函数确实可以采用一个cmp=...参数,该参数是两个值之间的比较器。从,这个参数已经被删除。

用键排序更有效,因为它避免了实现无效的比较函数:比较函数应该是反身,反对称和可传递的。一些比较功能不满足这些条件。