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?

Asked By: user3805057

||

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)
Answered By: Brian
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.