通过python中的自定义比较器对元组列表进行排序

Sha*_*ari 3 python sorting colors

我有一个如下所示的元组列表: [(image, rgb tuple, float), (image, rgb tuple, float) ...]

我想按 rgb 值对这个列表进行排序。我得到了一个“目标”颜色,并且必须按照每个 rgb 元组与目标颜色的接近程度对列表进行排序。我有一个函数color_distance(c1, c2),它接受两种颜色并返回它们之间的距离。我想使用这个颜色距离函数作为比较器函数,通过每个元组的 rgb 值距离目标颜色对我的元组列表进行排序。

我可以通过选择排序对列表进行排序并使用我的 color_distance 函数进行比较,但我希望它排序更快/使用库函数。

我正在尝试sorted()在 python 中使用该函数,但不知道如何使用。

eNc*_*eNc 7

import math
#Euclidean distance
def color_distance(color, target):
    return math.sqrt((color[0] - target[0])**2 + (color[1] - target[1])**2 + (color[2] - target[2])**2)

blueish = (93, 142, 170)
colors = [('Magenta',(216, 22, 266), 0.5), ('Yellow', (226, 226, 22), 0.95), ('Pink', (249, 159, 159), 0.75)]
sorted(colors, key=lambda c: color_distance(c[1], blueish))
Run Code Online (Sandbox Code Playgroud)

输出:

[('Pink', (249, 159, 159), 0.75),
 ('Magenta', (216, 22, 266), 0.5),
 ('Yellow', (226, 226, 22), 0.95)]
Run Code Online (Sandbox Code Playgroud)