2013-06-02 33 views
0

我想從列表中產生5個數字,但我不知道我該怎麼做? 我知道如何隨機模塊中使用的選擇,但我希望它這樣從列表中選擇多個整數:如何從列表中生成5個數字?

randomnumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

還是我必須做手工,例如:

num1 = choice(randomnumbers) 
num2 = choice(randomnumbers) 

等..

任何幫助,將不勝感激

+1

重複的選擇允許,或者你從列表中選擇所需五種不同的號碼? – Aya

回答

3

使用random.sample() function

from random import sample 
picked = sample(randomnumbers, 5) 

此選取5 不同的數字從輸入列表中。

如果重複號碼是允許的,一個列表解析會做random.choice會做:

from random import choice 
picked = [choice(randomnumbers) for _ in range(5)] 

示範:

>>> from random import sample, choice 
>>> sample(randomnumbers, 5) 
[1, 0, 9, 3, 2] 
>>> [choice(randomnumbers) for _ in range(5)] 
[1, 6, 5, 5, 0] 
相關問題