Generating a Random Hex Color in Python

前端 未结 15 1717
悲&欢浪女
悲&欢浪女 2020-11-29 01:36

For a Django App, each \"member\" is assigned a color to help identify them. Their color is stored in the database and then printed/copied into the HTML when it is needed. T

相关标签:
15条回答
  • 2020-11-29 02:32
    import random
    
    def generate_color():
        color = '#{:02x}{:02x}{:02x}'.format(*map(lambda x: random.randint(0, 255), range(3)))
        return color
    
    0 讨论(0)
  • 2020-11-29 02:33

    Just store them as an integer with the three channels at different bit offsets (just like they are often stored in memory):

    value = (red << 16) + (green << 8) + blue
    

    (If each channel is 0-255). Store that integer in the database and do the reverse operation when you need to get back to the distinct channels.

    0 讨论(0)
  • 2020-11-29 02:34
    import random
    r = lambda: random.randint(0,255)
    print('#%02X%02X%02X' % (r(),r(),r()))
    
    0 讨论(0)
提交回复
热议问题