Reputation: 377
Based on the probabilities of p, if p < 0.5 I would like to take letters of the corresponding positions of list1.
For example:
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)
Output is:
[ 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 ]
So based on the probabilities I would like my output to be:
['A', 'E']
['C', 'D', 'E']
['A']
['A', 'C']
['E']
Upvotes: 0
Views: 228
Reputation: 11183
Just another option:
[ [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']]
Upvotes: 1
Reputation: 4607
you can apply direct less than operator if you change your list
to 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])
Out:
['C']
['A' 'D']
['A' 'B' 'C' 'D']
['A' 'B' 'E']
['A' 'B' 'D']
Upvotes: 1
Reputation: 711
One way to solve this is with np.where, as suggested in another answer here.
Alternatively, in the style of functional programming, filter the list of letters by a function that "tosses the coin", namely:
filter(lambda letter: np.random.uniform() < 0.5, list1)
Or, equivalently:
(letter for letter in list1 if np.random.uniform() < 0.5)
Upvotes: 0
Reputation: 2882
Use np.where
to get the indices where the values are less than 0.5 and then print those elements:
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']
Upvotes: 3