Scott Pickslay
Scott Pickslay

Reputation: 25

how to pick a value from a list where the number in the list is its % chance of being picked

Essential, what i have is a list like this: Thislist = [20, 34, 46]

And i want it so when randomly picking a number, the first number will have a 20% chance of being picked, the 2nd number will have a 34% chance of being picked, and the 3rd number will have a 46% chance of being picked.

Upvotes: 0

Views: 299

Answers (3)

Nick
Nick

Reputation: 147146

As long as the numbers are integers adding to 100 then probably the simplest way to do this is to create a list which has each number repeated that many times in it, and then take a random choice from that list.

import random

Thislist = [20, 34, 46]
l = [n for v in Thislist for n in [v] * v]
print(random.choice(l))

Example test code:

res = {}
for _ in range(1000000):
    c = random.choice(l)
    res[c] = res.get(c, 0) + 1
    
print(res)

Sample output:

{46: 459771, 20: 200242, 34: 339987}

A note about performance.

There is obviously a setup cost here in forming the list l. If there are only to be a few selections from made from the list, @TharunK's answer is more efficient. However beyond that small number, random.choice is enough faster (~4x from my testing) than random.choices to make this solution far more efficient.

Upvotes: 2

Tharun K
Tharun K

Reputation: 1180

You can make use of random.choices()

Example

import random
    
num = [20, 34, 46]
for i in range(10):
    item = random.choices(num,num)
    print("Iteration:", i, "Weighted Random choice is", item[0])

Reference: https://docs.python.org/3/library/random.html#random.choices

Upvotes: 2

Buddy Bob
Buddy Bob

Reputation: 5889

Here is an example

import random
Thislist = [num for n in [[20]*20,[34]*34,[46]*46] for num in n]
print(random.choice(Thislist))

Upvotes: 0

Related Questions