[英]choosing non-equal random integers from an array (python)
我是python的新手。 我需要在1到100之間拉出5個隨機數。但是,這五個數字不能相同。 我正在考慮創建一個向量(范圍(1,101))並從向量中提取隨機值,然后創建一個循環,表明如果第二個繪制等於第一個繪制,則繪制另一個隨機數,如果之后的繪制等於前兩次繪制等等,直到拉出5個不等的隨機數。 有沒有更優雅的方式來做到這一點?
使用random.sample
:
>>> from random import sample
>>> sample(range(1, 101), 5)
[86, 90, 20, 72, 49]
你想要的是Fisher-Yates shuffle的一個變種。 我不'做'python(我喜歡的是一個Java人),但是,它很簡單......
以有序的方式創建源'set'(數組從1到101)的數組。
然后你要做的是在array.size - 1
last
設置一個變量,並執行以下操作:
int[] ret = new int[5] // return array of 5 members.
for (int i = 0; i < 5; i++) { // 5 is the number of values you want.
int rand = random(last + 1) // get a random integer from 0 to last (includes last)
# put the value at array[rand] in your return array var
ret[i] = array[rand]
# move the value at the end to the value we just copied out:
array[rand] = array[last]
# decrease the size of the values we can select from:
last--;
}
這樣您就可以從集合中選擇5個隨機值。 沒有重復,都具有相同的概率。
完整的Fisher-yates shuffle可以在整個陣列中就地執行此操作。 我只是使用你需要的算法的一部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.