How to pick a random no from a list (contain 1 to n values) with certain thresold value?
Question:
I have a list like the below:
l=[1,2,3,4,5]
thresold value = 0.5
From this list I want to pick a random number which is above the thresold value (in this case 0.5).
How can I achieve this?
Answers:
You can use a list comprehension
to filter it and then random.choice()
to get a random one. See below…
import random
l = [1,2,3,4,5]
threshold_value = 4
r = random.choice([x for x in l if x>threshold_value])
print(r)
I have a list like the below:
l=[1,2,3,4,5]
thresold value = 0.5
From this list I want to pick a random number which is above the thresold value (in this case 0.5).
How can I achieve this?
You can use a list comprehension
to filter it and then random.choice()
to get a random one. See below…
import random
l = [1,2,3,4,5]
threshold_value = 4
r = random.choice([x for x in l if x>threshold_value])
print(r)