2012-01-29 203 views
2

給定顏色= [「紅色」,「藍色」,「綠色」,「黃色」,「紫色」,「橙色」,「白色」,「黑色」] 生成並打印50個隨機顏色的列表。你將需要使用隨機模塊來獲得隨機數。使用範圍和地圖生成所需數量的數字。然後使用地圖將數字轉換爲顏色。打印結果。如何在python中生成50個隨機顏色的列表?

這是我一直在考慮一個問題,這是我到目前爲止的代碼

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

number=random.randint(1,9) 

number.range(50) 

我假設這已經提出,挑選1-9之間的隨機數的變量,然後將它們使得50 ?我現在需要一些連接數字和顏色的方法..我知道這個問題很模糊,但如果任何人都可以指向正確的方向,那就太棒了!

回答

1

由於某種原因,您的問題需要使用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(),是迄今爲止確定的最佳途徑答案。

+0

多數民衆贊成在完美的,我同意其他方式要容易得多,但顯然這是我需要的方式!感謝您的幫助 ! – 2012-01-29 23:25:16

1

您可以使用一個簡單的列表理解爲這樣的:

[ colour[random.randint(0,len(colour)-1)] for x in range(0,50) ] 

colour[i]意味着在colour列表中i個元素。根據您的建議,從0到列表的長度減1,創建一個隨機整數len(colour)-1,其中random.randint。這與range(1,50)重複50次。列表理解中的虛擬迭代器值x被忽略。

希望這會有所幫助!

+0

有'random.choice'確切的東西......而'range(1,50)'只有49個選擇。 – Gandaro 2012-01-29 23:11:11

+0

@Gandaro好點! – danr 2012-01-29 23:16:33

5

你需要的是使用random.choice(seq) 50次通過它colour列表作爲參數。

像這樣:從seq隨機選擇的元件

rand_colours = [random.choice(colour) for i in range(50)] 

random.choice(seq)回報。

+0

不錯!是否有一些與Haskell的'replicate'和'replicateM'等價的表達式多次計算並返回結果列表? – danr 2012-01-29 23:03:39

+0

@danr我不認爲有直接的等價物。 [python教程](http://docs.python.org/library/itertools.html#itertools.starmap)給出了一個如何使用'itertools.starmap'重複函數調用n次的例子。它甚至在'repeatfunc'中使用'random.random'。無論如何,它看起來使用'for'是最簡單的方法。 – soulcheck 2012-01-29 23:30:46