如何在python中生成50种随机颜色的列表?

Car*_*ssi 3 python random map range

给定color = ["red","blue","green","yellow","purple","orange","white","black"]生成并打印50种随机颜色的列表.您将需要使用随机模块来获取随机数.使用范围和地图生成所需的数字量.然后使用map将数字转换为颜色.打印结果.

这是一个我已经给出的问题,到目前为止这是我的代码

colour = [ "red", "blue", "green", "yellow", "purple", "orange", "white", "black" ]

number=random.randint(1,9)

number.range(50)
Run Code Online (Sandbox Code Playgroud)

我假设这个变量在1-9之间选择随机数,然后生成其中的50个?我现在需要一些方法将数字与颜色联系起来..我知道这个问题很模糊,但如果有人能指出我正确的方向,那就太棒了!

sou*_*eck 7

你需要的是使用random.choice(seq)50次传递colour列表作为参数.

像这样:

 rand_colours = [random.choice(colour) for i in range(50)]
Run Code Online (Sandbox Code Playgroud)

random.choice(seq)从中返回随机选择的元素seq.


Jad*_*nik 5

如果你想要 n 个随机的十六进制颜色,试试这个:

import random
get_colors = lambda n: list(map(lambda i: "#" + "%06x" % random.randint(0, 0xFFFFFF),range(n)))
get_colors(5) # sample return:  ['#8af5da', '#fbc08c', '#b741d0', '#e599f1', '#bbcb59', '#a2a6c0']
Run Code Online (Sandbox Code Playgroud)


Cal*_*ngh 3

由于某种原因,您的问题需要使用map. 如果不直接给出答案,就很难帮助解决这个问题,特别是因为这些类型的操作都是俏皮话。首先,使用 map 和 range 获取所需范围内的随机数列表:

>>> nums = map(lambda x : random.randint(0,7), range(50))
>>> nums
[6, 6, 2, 4, 7, 6, 6, 7, 1, 4, 3, 2, 6, 1, 1, 2, 2, 0, 7, 
3, 6, 1, 5, 2, 1, 2, 6, 0, 3, 0, 2, 6, 0, 6, 3, 5, 0, 7, 
2, 5, 4, 1, 0, 0, 1, 4, 3, 3, 0, 3]
Run Code Online (Sandbox Code Playgroud)

x请注意,未使用lambda 的参数。这至少是我不会在这里使用地图的原因之一。然后,使用数字列表,将索引函数映射到数字上以获得颜色列表:

>>> cols = map(lambda i: colour[i], nums)
>>> cols
['white', 'white', 'green', 'purple', 'black', 'white', 'white', 
'black', 'blue',     'purple', 'yellow', 'green', 'white', 
'blue', 'blue', 'green', 'green', 'red', 'black', 'yellow', 
'white', 'blue', 'orange', 'green', 'blue', 'green', 'white', 
'red', 'yellow', 'red', 'green', 'white', 'red', 'white', 
'yellow', 'orange', 'red', 'black', 'green', 'orange', 'purple', 
'blue', 'red', 'red', 'blue', 'purple', 'yellow', 'yellow', 'red', 
'yellow']
Run Code Online (Sandbox Code Playgroud)

Soulcheck 在列表理解中给出的答案random.choice()是迄今为止确定答案的最佳方法。