我想創建一個包含 '1' 值而不是其他亂數的串列。
假設我希望 60% 的 '1' 出現在 10 個元素中。所以 1 的 6 個元素和隨機的 4 個元素。這就是我的方法。
import numpy as np
import random
# to avoid generating 1s..
list_60 = np.random.randint(2,11, 10)
array([ 6, 2, 8, 6, 6, 3, 5, 10, 6, 8])
count = 0
percentage = int(len(list_60)*(0.6) 0.5)
for i in range(0,len(list_60)):
if count < percentage:
list_60[i]=0
count = 1
list_60
array([ 1, 1, 1, 1, 1, 1, 5, 10, 6, 8])
random.shuffle(list_60)
array([ 1, 1, 1, 6, 1, 5, 1, 1, 8, 10])
辦理步驟:
- 創建從 2 到 10 的 randint。
- 回圈每個元素并基于百分比。并將元素更改為1s。
- 隨機播放串列以獲得更多變化。
我不認為這是產生更多 1 的聰明方法。有沒有花哨/智能的方法來創建加權隨機性?
任何幫助,將不勝感激。
uj5u.com熱心網友回復:
您可以獲取索引的隨機子集,然后將這些索引設定為 1:
import numpy as np
arr = np.random.randint(2, 11, 10)
index = np.random.choice(len(arr), int(len(arr) * 0.6), replace=False)
arr[index] = 1
print(arr)
您也可以在沒有 numpy 的情況下執行此操作:
import random
arr = [random.randint(2, 11) for _ in range(10)]
index = random.sample(range(len(arr)), int(len(arr) * 0.6))
for i in index:
arr[i] = 1
print(arr)
上述兩種實作使用 10 6 個隨機位。從技術上講,您只需要 4 4(亂數為 4,隨機位置為 4(感謝@KellyBundy 注意到這一點)。您可以在 numpy 中實作這一點:
import numpy as np
arr = np.ones(10)
index = np.random.choice(len(arr), int(len(arr) * 0.4), replace=False)
arr[index] = np.random.randint(2, 11, len(index))
print(arr)
或者使用普通的 python 更簡單:
import random
arr = [1] * 10
for i in random.sample(range(len(arr)), int(len(arr) * 0.4)):
arr[i] = random.randint(2, 11)
print(arr)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/424163.html
