簡體   English   中英

如何執行多個 random.choices 測試

[英]How can I perform multiple random.choices tests

我有一個名為彈珠的列表。 marbels = 10.000 件物品(5000 件藍色和 5000 件紅色)

我想執行一個測試,其中“def A1.primo():”將計算並返回測量的隨機事件,在較小的樣本中比在較大的樣本中重復得更多。 使用 (k=4, k=7)

import random

marbles = ["RED" for _ in range(5000)] + ["BLUE" for _ in range(5000)]
A = random.choices(marbles, k=4) 
print(A) # this will print a list of 4 random Items from the list

我如何優化代碼,然后將返回的數字從 A1.primo 保存到 csv.file

使用 for 循環。

for x in range(4):
    print(random.choice(marbles))

有和沒有替換的采樣

了解有放回抽樣和無放回抽樣之間的區別很重要。 假設我們有一袋 1 個藍色和 2 個紅色彈珠,而你 select 2 個彈珠。 如果您在拉出第一個彈珠后將彈珠放回原位,則可能會得到 2 個藍色彈珠。 這稱為放回抽樣。 使用random.choice放回的抽樣。

random.choices() 和 random.sample()

您可以使用random模塊中的choices() function 提取多個元素。 例如,從一袋 1 個紅色和 2 個藍色彈珠中抽取 4 個彈珠並進行替換:

>>> import random
>>> marbles = ['red'] * 1 + ['blue'] * 2
>>> random.choices(marbles, k=4)
['red', 'blue', 'blue', 'blue']

您可以使用sample function 使用random模塊進行放回采樣:

>>> random.sample(marbles, 4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/homebrew/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/random.py", line 482, in sample
    raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative

正如預期的那樣,這給出了一個錯誤。 你不能從一袋 3 顆彈珠中取出 4 顆彈珠。現在如果我們在袋子里放 1000 顆紅色彈珠和 2000 顆藍色彈珠,我們會得到:

>>> marbles = ['red'] * 1000 + ['blue'] * 2000
>>> random.sample(marbles, 4)
['blue', 'blue', 'blue', 'red']

Memory 用法和權重

上面例子的一個可能的問題是,如果你有更多的彈珠,你需要很多 memory。因此, choice() function 有一個weights參數。 你可以像這樣使用它:

>>> marbles = ['red', 'blue']
>>> weights = [1000, 2000]
>>> random.choices(marbles, weights=weights, k=4)
['blue', 'blue', 'blue', 'red']

可悲的是, random模塊沒有 function 用於不使用權重進行替換的采樣。

使用 for 循環重復采樣

最后,我們需要計算結果。 一種更高級的方法是使用collections模塊中的字典和defaultdict 作為替代方案,我們將創建一個結果列表,並使用該列表的一組循環遍歷不同的結果。

隨機導入

SAMPLE_SIZE = 4 REPEAT_SAMPLING = 100

outcomes = []
marbles = ['red'] * 5000 + ['blue'] * 5000

for i in range(REPEAT_SAMPLING):
    outcome = ', '.join(random.sample(marbles, SAMPLE_SIZE))
    outcomes.append(outcome)

for outcome in set(outcomes):
    print(f'{outcome} appeared {outcomes.count(outcome)} times out of {REPEAT_SAMPLING}')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM