由于某种原因,您的问题需要使用map
。没有直接给出答案就很难帮助解决这个问题,特别是因为这些操作是单线的。要开始使用地图和范围,以获得需要的范围内的随机号码的清单:
>>> 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]
观察该参数拉姆达,不使用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']
通过soulcheck给出的答案,在列表理解使用random.choice()
,是迄今为止确定的最佳途径答案。
多数民众赞成在完美的,我同意其他方式要容易得多,但显然这是我需要的方式!感谢您的帮助 ! – 2012-01-29 23:25:16