Sort (hex) colors to match rainbow

0 votes
I have a list of colors represented in hex - I need to sort them to match the order of colors in a rainbow. - I could hardcode a sort order - but I feel there's a cleaner way.

Can anyone help me with a better way to solve this?
Jul 17 in Python by ana1504.k
• 7,870 points
30 views

1 answer to this question.

0 votes

Here's a function that, given a color specification in hex RGB, returns its HSV color:

import colorsys

def get_hsv(hexrgb):
    hexrgb = hexrgb.lstrip("#")   # in case you have Web color specs
    r, g, b = (int(hexrgb[i:i+2], 16) / 255.0 for i in xrange(0,5,2))
    return colorsys.rgb_to_hsv(r, g, b)

Now you can use this to sort your list of RGB hex colors by hue:

color_list = ["000050", "005000", "500000"]  # GBR
color_list.sort(key=get_hsv)
print color_list
answered Jul 17 by SDeb
• 13,160 points

Related Questions In Python

0 votes
1 answer

How to sort Counter by value using python?

Use the Counter.most_common() method, it'll sort the items for you: >>> ...READ MORE

answered May 22, 2018 in Python by charlie_brown
• 7,710 points
1,519 views
0 votes
1 answer

How to sort a list of strings?

Basic answer: mylist = ["b", "C", "A"] mylist.sort() This modifies ...READ MORE

answered Jun 4, 2018 in Python by ariaholic
• 7,320 points
32 views
0 votes
1 answer

How to sort a list of strings?

Try  items = ["live", "like", "code", "cool", "bug"] ...READ MORE

answered Jul 27, 2018 in Python by Priyaj
• 56,520 points
18 views
0 votes
1 answer

How to sort dictionary by value python

This would work: d = sorted(data, key = ...READ MORE

answered Nov 2, 2018 in Python by Nabarupa
60 views
+1 vote
1 answer

Implement Quicksort in Python

This will help you. def sort(array=[2,5,1,6,9,8,7,10,21,12]): ...READ MORE

answered Oct 30, 2018 in Python by Priyaj
• 56,520 points
47 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 169 views
0 votes
1 answer

Python sort() function arguments

Both sort and sorted have three keyword arguments: cmp, key and reverse. L.sort(cmp=None, key=None, reverse=False) -- ...READ MORE

answered Oct 8, 2018 in Python by SDeb
• 13,160 points
225 views
0 votes
1 answer

How to convert string into epoch time?

you are passing the parsed datetime object to ...READ MORE

answered Sep 21, 2018 in Python by SDeb
• 13,160 points
96 views