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

2024-03-28 12:06:01 发布

您现在位置:Python中文网/ 问答频道 /正文

基于p的概率,如果p<;0.5,我想取列表1对应位置的字母。你知道吗

例如:

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

Tags: inlt列表forsizenp字母range
3条回答

如果将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']]

使用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']

相关问题 更多 >