python颜色随机生成器的实例代码

yipeiwu_com6年前Python基础

1. 代码:

def random_color(number=number):
  color = []
  intnum = [str(x) for x in np.arange(10)]
  #Out[138]: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
  alphabet = [chr(x) for x in (np.arange(6) + ord('A'))]
  #Out[139]: ['A', 'B', 'C', 'D', 'E', 'F']
  colorArr = np.hstack((intnum, alphabet))
  #Out[142]: array(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C','D', 'E', 'F'], dtype='<U1')
  for j in range(number):
    color_single = '#'
    for i in range(6):
      index = np.random.randint(len(colorArr))
      color_single += colorArr[index]
    #Out[148]: '#EDAB33'
    color.append(color_single)
  return color
  del color, intnum, alphabet, colorArr, j, i, color_single, index, number
 
color = random_color(number=6)
#Out[150]: ['#81D4D4', '#70344F', '#DF91B1', '#7EE250', '#C47BC3', '#9F88D5'] 

2. 小记:

1.字符转数字 ord('a') 97
数字转字符 chr(71) ‘G'

2.[]与()的区别

(np.arange(6) + ord('A'))
Out[158]: array([65, 66, 67, 68, 69, 70])
type((np.arange(6) + ord('A')))
Out[166]: numpy.ndarray
[np.arange(6) + ord('A')]
Out[159]: [array([65, 66, 67, 68, 69, 70])]
type([np.arange(6) + ord('A')])
Out[165]: list

总结

以上所述是小编给大家介绍的python颜色随机生成器的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

Python基于贪心算法解决背包问题示例

本文实例讲述了Python基于贪心算法解决背包问题。分享给大家供大家参考,具体如下: 贪心算法(又称贪婪算法)是指,在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优...

Python如何通过subprocess调用adb命令详解

前言 本文主要给大家介绍了关于使用Python通过subprocess调用adb命令,subprocess包主要功能是执行外部命令(相对Python而言)。和shell类似。 换言之除...

浅谈Python 的枚举 Enum

枚举是常用的功能,看看Python的枚举. from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'A...

教你用一行Python代码实现并行任务(附代码)

Python在程序并行化方面多少有些声名狼藉。撇开技术上的问题,例如线程的实现和GIL,我觉得错误的教学指导才是主要问题。常见的经典Python多线程、多进程教程多显得偏"重"。而且往往...

对PyTorch torch.stack的实例讲解

不是concat的意思 import torch a = torch.ones([1,2]) b = torch.ones([1,2]) torch.stack([a,b],1) (...