python3中的自定义比较功能

Ezi*_*yev 3 python python-3.x

我想按照它们到原点(0,0)的距离按升序对2D坐标系中的点进行排序.我找到了这个并尝试了一些东西,但仍然无法得到理想的结果.

这是我的代码:

from functools import cmp_to_key

def my_comp(point1, point2):
    return point1[0]*point1[0] + point1[1]*point1[1] < point2[0]*point2[0] + point2[1]*point2[1]

points = [ [3.1, 4.1], [0.9, 0.8], [1.0, 1.0] ]
sorted(points, key=cmp_to_key(my_comp))
print(points)
Run Code Online (Sandbox Code Playgroud)

结果:

[[3.1, 4.1], [0.9, 0.8], [1.0, 1.0]]
Run Code Online (Sandbox Code Playgroud)

预期:

[[0.9, 0.8], [1.0, 1.0], [3.1, 4.1]]
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 8

1)你的my_cmp()函数应该返回三个值中的一个(+, - 或0取决于比较),但你只返回两个(True和False).

2)你从中获取返回值sorted().sorted()不修改其参数,它返回它的排序副本.

3)不要使用cmp功能.它们很难描述,很难实现.而是使用关键功能.

怎么样:

def my_key(point1):
    return point1[0]*point1[0] + point1[1]*point1[1]

points = [ [3.1, 4.1], [0.9, 0.8], [1.0, 1.0] ]
points = sorted(points, key=my_key)
print(points)

assert points == [ [0.9, 0.8], [1.0, 1.0], [3.1, 4.1] ]
Run Code Online (Sandbox Code Playgroud)