鉴于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个?我现在需要一些方法将数字与颜色联系起来..我知道这个问题很模糊,但如果有人能指出我正确的方向,那就太棒了!
解决方法:
出于某种原因,您的问题需要使用地图.如果不直接给出答案,很难帮助解决这个问题,特别是因为这些操作是单行的.首先,使用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(),是迄今为止确定答案的最佳方法.
标签:python,random,range,map
来源: https://codeday.me/bug/20190716/1481494.html