python - 根据 for 循环中的概率打印列表的元素
问题描述
基于 p 的概率,如果 p < 0.5 我想取 list1 对应位置的字母。
例如:
for i in range(5):
list1 = ['A', 'B', 'C', 'D', 'E']
p = np.random.uniform(low= 0.0, high= 1.0, size=5)
print(p)
输出是:
[ 0.46565909 0.741431 0.65590764 0.87347741 0.38465195]
[ 0.62172525 0.80688763 0.40391766 0.28042554 0.34544989]
[ 0.00138961 0.56959351 0.69043625 0.59473154 0.84042555]
[ 0.18535428 0.63470281 0.27882709 0.78731892 0.63624727]
[ 0.89383216 0.72008758 0.66048462 0.94064897 0.1484418 ]
因此,根据概率,我希望我的输出是:
['A', 'E']
['C', 'D', 'E']
['A']
['A', 'C']
['E']
解决方案
用于np.where
获取值小于 0.5 的索引,然后打印这些元素:
for i in range(5):
list1 = ['A', 'B', 'C', 'D', 'E']
mask = np.where(np.random.uniform(low= 0.0, high= 1.0, size=5) < 0.5)
print([list1[i] for i in mask[0]])
#output (The output is stochastic meaning they will change on each iteration unless you use fixed random state)
['C']
['A', 'B', 'C', 'E']
['D', 'E']
['A', 'C', 'D']
['B', 'C', 'E']