给定一个list的set及set中元素被选取的概率,从list中按set元素的概率抽取若干个数

import random
import numpy as np
a = list(range(0, 9))   #a = [0,1,2,3,4,5,6,7,8]
a_ = list(range(0, 10)) #a_ = [0,1,2,3,4,5,6,7,8,9]
b = a * 5 + [9] * 2     #b = [0,1,2,3,4,5,6,7,8,...,9,9]
random.shuffle(b)

p1 = (1/5) / ((1/5)*9 + (1/2))
p2 = (1/2) / ((1/5)*9 + (1/2))
print(p1, p2)           #0.08695652173913045 0.2173913043478261

def random_choice(num_list, targets, size, p):
    targets_ = targets.copy()
    collector = []
    for i in range(size):
        sign = True
        ele = np.random.choice(num_list, 1, p)[0]
        while sign:
            if ele in targets_:
                collector.append(ele)
                targets_.remove(ele)
                sign = False
            else:
                ele = np.random.choice(num_list, 1, p)[0]
    return collector

samples = random_choice(a_, b, 10, p=[*([p1]*9), p2])
print(samples)         #[7, 1, 2, 9, 1, 5, 6, 4, 5, 9]

猜你喜欢

转载自blog.csdn.net/qq_36076233/article/details/110130934