Generating a Random Hex Color in Python

前端 未结 15 1795
悲&欢浪女
悲&欢浪女 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:13

    Would like to improve upon this solution as I found that it could generate color codes that have less than 6 characters. I also wanted to generate a function that would create a list that can be used else where such as for clustering in matplotlib.

    import random
    
    def get_random_hex:
        random_number = random.randint(0,16777215)
    
        # convert to hexadecimal
        hex_number = str(hex(random_number))
    
        # remove 0x and prepend '#'
        return'#'+ hex_number[2:]
    

    My proposal is :

    import numpy as np 
    
    def color_generator (no_colors):
        colors = []
        while len(colors) < no_colors:
            random_number = np.random.randint(0,16777215)
            hex_number = format(random_number, 'x')
            if len(hex_number) == 6: 
                hex_number = '#'+ hex_number
                colors.append (hex_number)
        return colors
    

提交回复
热议问题