如何随机选择列表的值? [英] How to randomly select values for a list?
问题描述
我使用的是 Python 2.7
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
显然上面的代码不起作用,但我不确定如何继续.如果我可以更改某个字符串被选中的可能性,例如 50% 的红色几率、30% 的蓝色几率和 20% 的黄色几率,这也会有所帮助.
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.
推荐答案
您可以使用 numpy.random.choice
.p
参数允许您指定与每个条目关联的概率.
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']
要确认这是有效的,请使用大小为 30,000 而不是 3 的结果,并让大数定律发挥作用.
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}
这篇关于如何随机选择列表的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!