python - 通过python中的自定义比较器对元组列表进行排序
问题描述
我有一个如下所示的元组列表:
[(image, rgb tuple, float), (image, rgb tuple, float) ...]
我想按 rgb 值对这个列表进行排序。我得到了一个“目标”颜色,并且必须按照每个 rgb 元组与目标颜色的接近程度对列表进行排序。我有一个名为的函数color_distance(c1, c2)
,它接受两种颜色并返回它们之间的距离。我想将此颜色距离函数用作比较器函数,以按每个元组的 rgb 值与目标颜色的距离对我的元组列表进行排序。
我可以通过选择排序对列表进行排序并使用我的 color_distance 函数进行比较,但我希望它更快地排序/使用库函数。
我正在尝试sorted()
在 python 中使用该函数,但不知道如何。
解决方案
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)]
推荐阅读
- php - 如何显示这些记录特定于它们包含的数据?
- php - 在 127.0.0.1:8000 上使用 PHP 内置服务器
- python - 如果文本文件中的前 10 个字符匹配 - 写入新文件
- javascript - 如何使用 JavaScript 触发 jQuery 更改功能?
- formatting - 如何使用 PHPExcel 将百分比数字格式化为 Excel 百分比?
- javascript - three.js - “未捕获的类型错误:无法读取未定义的属性 'center' - three.js:6754”当我添加另一个网格时正在发生
- ansible - Jenkis 管道具有额外的 ansible 凭据
- javascript - 仅打印多个文本区域
- markdown - Teams 中的 QnA Maker Bot 格式问题
- python - 使用 kaldi_io (python) UnicodeDecodeError 读取 .scp 文件