Here are the basic steps to an app I’m writing in Python:
- Generate a list of random colors
- Create a mapping of each of those colors, indexed by that color’s distance to a “source color” in 3D (r, g, b) space. (For instance, orange (255, 150, 0) is closer to red(255, 0, 0) than dark blue (0, 0, 100). By now, I have a list of tuples of the format (distance, color).
- Sort that list of tuples based on the distances I had calculated (from lowest, to highest).
- Retrieve a list of the sorted colors
Here is my function, and I get the following error: TypeError: ‘int’ object has no attribute ‘_getitem_’ on the line sorted_by_dist = sorted(colorMap, key=lambda tup: tup[0])
# Sorts a list of colors according to distance from the source color
def sort_colors(colors, source):
colorMap = ()
sortedColors = list()
for i in range(len(colors)):
dist = dist_3d(colors[i], source)
colorMap = colorMap + (dist, colors[i])
sorted_by_dist = sorted(colorMap, key=lambda tup: tup[0])
for (d, c) in sorted_by_dist:
sortedColors.append(c)
return sortedColors
Assuming my dist_3d() function is correct and returns an integer value (it is, and does), what am I doing wrong? I don’t understand.
You are building your
colorMapas a big single dimensional tuple, with the first index being anint. So yourlambdais being passed anintand then you try to index into it.You probably want a list of tuples:
In terms of an approach to sorting colors, I have actually used a
kdtreemodule for this, loaded up with all my RGB tuples. Then I can ask it for N closest colors to a given color tuple: