基于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']
答案 0 :(得分:3)
使用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']
答案 1 :(得分:1)
如果您将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']
答案 2 :(得分:1)
另一个选择:
[ [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']]
答案 3 :(得分:0)
解决此问题的一种方法是使用np.where,如此处另一个答案所建议。
或者,以函数式编程的方式,通过“抛硬币”功能过滤字母列表,即:
filter(lambda letter: np.random.uniform() < 0.5, list1)
或者,等效地:
(letter for letter in list1 if np.random.uniform() < 0.5)