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 4,494 views

## 1 answer to this question.

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
• 13,300 points

## How to sort Counter by value using python?

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

## How to sort a list of strings?

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

## How to sort a list of strings?

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

## How to sort dictionary by value python

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

+1 vote

## how do i change string to a list?

suppose you have a string with a ...READ MORE

## how can i randomly select items from a list?

You can also use the random library's ...READ MORE

+1 vote

## how can i count the items in a list?

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