Python numpy+random按概率选择列表中某一元素

输出100次1,2,3,4的值,其中1出现的概率为 10 % 10\% ,2出现的概率为 0 0 ,3出现的概率为 70 % 70\% ,4出现的概率为 20 % 20\%

import numpy as np

np.random.seed(0)
p = np.array([0.1, 0.0, 0.7, 0.2])
for i in range(100):
    index = np.random.choice([1, 2, 3, 4], p=p.ravel())
    print(index)
3
3
3
3
3
3
3
4
4
3
3
3
3
4
1
1
1
4
3
4
4
3
3
3
3
3
3
4
3
3
3
3
3
3
1
3
3
3
4
3
3
3
3
1
3
3
3
3
3
3
3
3
4
3
3
3
3
3
3
3
3
3
3
3
3
3
4
1
4
1
4
3
4
3
3
1
3
3
3
3
3
3
1
3
3
3
3
1
3
4
3
3
3
3
3
3
3
1
4
1

猜你喜欢

转载自blog.csdn.net/qq_44864262/article/details/108115891