由於某種原因,您的問題需要使用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