user3805057
user3805057

Reputation: 195

How to pick a random no from a list (contain 1 to n values) with certain thresold value?

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?

Upvotes: 2

Views: 56

Answers (1)

Brian
Brian

Reputation: 1667

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)

Upvotes: 4

Related Questions