4

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.

Shams Ansari
  • 762
  • 5
  • 12
  • Hard to be certain given the lack of detail in the question but perhaps `sorted(lst, lambda t: color_distance(t[1], target))`? – Nick Jun 20 '20 at 01:31
  • You can try `list.sort(key=your_compare_function)` – Nagabhushan S N Jun 20 '20 at 01:32
  • Does https://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-based-on-an-attribute-of-the-objects help? This is a common question, but it's hard to pin down an *exact* duplicate. – Karl Knechtel Jun 20 '20 at 02:43

1 Answers1

8
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)]
eNc
  • 1,021
  • 10
  • 23