How to randomly select values for a list?

2019-07-13 05:32发布

问题:

I'm using Python 2.7

To be clear, I don't want to randomize the items in the list. I want to make it so it's possible for certain strings not to show up at all. For example:

    r = "red"
    b = "blue"
    y = "yellow"
    rc = random colour
    myColours = [rc,rc,rc]
    print myColours

Obviously the code above wouldn't work, but I'm not sure how to proceed. It would also help if I could change how likely a certain string would be selected, like 50% odds of red, 30% odds of blue, and 20% odds of yellow.

回答1:

You can use numpy.random.choice. The p parameter allows you to specify the probabilities associated with each entry.

import numpy as np

r, b, y = 'red', 'blue', 'yellow'
my_colours = np.random.choice(a=[r, b, y], size=3, p=[.5, .3, .2])
print(my_colours) . # my_colours.tolist() if you want list output
# ['yellow' 'red' 'red']

To confirm this is working, use a result of size 30,000 rather than 3 and let the law of large numbers do its thing.

from collections import Counter

test = np.random.choice(a=[r, b, y], size=30000, p=[.5, .3, .2])
counts = Counter(test)

# Relative occurences:
dict(zip(counts.keys(), [count/30000 for count in counts.values()]))
{'blue': 0.30483333333333335,
 'red': 0.5000333333333333,
 'yellow': 0.19513333333333333}


回答2:

Although it will not help the OP using Python 2.7, for those using Python 3.6, random.choices is simple, includes weights and is part of the standard library.

Return a k sized list of elements chosen from the population with replacement.

Given

import random


r = "red"
b = "blue"
y = "yellow"

iterable = r, b, y
size = 3
wts = [.5, .3, .2]

Code

random.choices(iterable, k=size)
# ['red', 'yellow', 'yellow']

random.choices(iterable, weights=wts, k=size)
# ['red', 'red', 'red']