鉴于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)
我假设这个变量在1-9之间选择随机数,然后生成其中的50个?我现在需要一些方法将数字与颜色联系起来..我知道这个问题很模糊,但如果有人能指出我正确的方向,那就太棒了!
答案 0 :(得分:7)
您需要使用random.choice(seq)
50次传递colour
列表作为参数。
像这样:
rand_colours = [random.choice(colour) for i in range(50)]
random.choice(seq)
会从seq
返回随机选择的元素。
答案 1 :(得分: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]
观察到lambda的参数x
未被使用。这至少是我不在这里使用地图的原因之一。然后,使用数字列表,将索引函数映射到数字上以获取颜色列表:
>>> 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']
灵魂检查在列表理解中使用random.choice()
给出的答案是迄今为止确定答案的最佳方法。
答案 2 :(得分:1)
您可以使用简单的列表理解:
[ colour[random.randint(0,len(colour)-1)] for x in range(0,50) ]
colour[i]
表示i
列表中的colour
元素。根据您的建议,从0到列表长度减去一个len(colour)-1
,random.randint
创建一个随机整数。用range(1,50)
重复50次。
x
。
希望这有帮助!
答案 3 :(得分:1)
如果你想要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']
答案 4 :(得分:0)
获得 50 个十六进制颜色值的另一种解决方案:
def random_color():
return "#{}{}{}{}{}{}".format(*(random.choice("0123456789abcdef") for _ in range(6)))
colors = [random_color() for _ in range(50)]
print(*colors)