擅长:python、mysql、java
<p>这可能就是你要找的。对<a href="https://stackoverflow.com/questions/4265988/generate-random-numbers-with-a-given-numerical-distribution/">Generate random numbers with a given (numerical) distribution</a>中的解决方案的扩展。从分发中删除选定项,更新概率并返回<code>selected item, updated distribution</code>。没有证明有效,但应该给人一个好印象的想法。</p>
<pre><code>def random_distr(l):
assert l # don't accept empty lists
r = random.uniform(0, 1)
s = 0
for i in xrange(len(l)):
item, prob = l[i]
s += prob
if s >= r:
l.pop(i) # remove the item from the distribution
break
else: # Might occur because of floating point inaccuracies
l.pop()
# update probabilities based on new domain
d = 1 - prob
for i in xrange(len(l)):
l[i][1] /= d
return item, l
dist = [[1, 0.5], [2, 0.25], [3, 0.05], [4, 0.01], [5, 0.09], [6, 0.1]]
while dist:
val, dist = random_distr(dist)
print val
</code></pre>