基于for循环中的概率打印列表元素

Print elements of a list based on probabilities in for loop

根据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']

解决此问题的一种方法是使用 np.where,正如此处另一个答案中所建议的那样。

或者,在函数式编程风格中,通过 "tosses the coin" 函数过滤字母列表,即:

filter(lambda letter: np.random.uniform() < 0.5, list1)

或者,等价地:

(letter for letter in list1 if np.random.uniform() < 0.5)

如果将 list 更改为 numpy array

,则可以直接应用小于运算符
for i in range(5):
    list1 = np.asarray(['A', 'B', 'C', 'D', 'E'])
    p = np.random.uniform(low= 0.0, high= 1.0, size=5)
    print(list1[p < 0.5])

输出:

['C']
['A' 'D']
['A' 'B' 'C' 'D']
['A' 'B' 'E']
['A' 'B' 'D']

还有一个选择:

[ [l for r, l in zip(np.random.uniform(low= 0.0, high= 1.0, size=5), list1) if r > 0.5] for i in range(5) ]

#=> [['A'], ['D', 'E'], ['B', 'C'], ['D'], ['B', 'C', 'E']]