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, 2019 in Python by ana1504.k
• 7,910 points
4,926 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, 2019 by SDeb
• 13,300 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 23, 2018 in Python by charlie_brown
• 7,720 points
10,647 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 aryya
• 7,460 points
1,497 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
• 58,020 points
845 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
721 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
• 58,020 points
1,077 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 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,300 points
8,036 views
0 votes
1 answer

How to convert string into epoch time?

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

answered Sep 22, 2018 in Python by SDeb
• 13,300 points
6,788 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP