我正在寻找一种算法,根据每个元素的概率从25个元素的列表中选择12个。这些元素不能重复。
我尝试使用无替换的函数,但是当我进行1000次迭代以检查是否正确时,我无法让它保留权重。只有在使用replace = True函数时我才成功了。
由于该函数返回重复项,因此我清理列表以删除重复项。这样做会导致我获取每个数字的概率与一开始定义的不同。我知道错误在这里,我应该使用replace = False函数,但我无法得到结果。
我尝试使用无替换的函数,但是当我进行1000次迭代以检查是否正确时,我无法让它保留权重。只有在使用replace = True函数时我才成功了。
由于该函数返回重复项,因此我清理列表以删除重复项。这样做会导致我获取每个数字的概率与一开始定义的不同。我知道错误在这里,我应该使用replace = False函数,但我无法得到结果。
import numpy as np
from collections import Counter
nameList = ['AAAAAA', 'B', 'C', 'D','E','F','G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P','Q','R','S','T','U','V','W','X','ZZZZZZZZZZZZZZZZ']
probability_nameList = [0.10, 0.01, 0.02, 0.03, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04, 0.04]
sampleNames =[]
sampleNamesControl =[]
cleaned_result = []
test_list = []
for i in range(1000):
sampleNames += np.random.choice(nameList, 100,replace=True, p=probability_nameList)
for item in sampleNames:
if not item in cleaned_result:
cleaned_result += [item]
sampleNames =[]
test_list += cleaned_result[0:12]
cleaned_result = []
print(Counter(test_list))
响应:
Counter({'AAAAAA': 832, 'F': 522, 'X': 513, 'ZZZZZZZZZZZZZZZZ': 506, 'I': 505, 'L': 504, 'N': 501, 'S': 499, 'T': 498, 'U': 496, 'R': 492, 'O': 491, 'J': 489, 'P': 488, 'E': 487, 'V': 485, 'K': 482, 'Q': 479, 'H': 473, 'G': 471, 'M': 468, 'W': 461, 'D': 404, 'C': 297, 'B': 157})
从上述公式可以看出,AAAAA必须比B大10倍,但实际情况并不是这样。 P(AAAAA)= 10xP(B)