Sort a list of tuples by a custom comparator in python

Viewed 631

I have a list of tuple that looks like the following: [(image, rgb tuple, float), (image, rgb tuple, float) ...]

I want to sort this list by the rgb value. I am given a "target" color and have to sort the list by how close each rgb tuple is to the target color. I have a function called color_distance(c1, c2) that takes in two colors and returns the distance between them. I want to use this color distance function as a comparator function to sort my list of tuples by each tuple's rgb value distance to the target color.

I could sort the list by selection sort and use my color_distance function to compare but I want it sorted faster/ using a library function.

I am trying to use the sorted() function in python but don't know how.

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

Output:

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