首页 > 解决方案 > 通过python中的自定义比较器对元组列表进行排序

问题描述

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

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

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

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

标签: pythonsortingcolors

解决方案


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))

输出:

[('Pink', (249, 159, 159), 0.75),
 ('Magenta', (216, 22, 266), 0.5),
 ('Yellow', (226, 226, 22), 0.95)]

推荐阅读