<p>这里有一些东西似乎可以工作并满足您的所有规范(主观上看起来很快)。请注意,第二个数与第一个数不相同的约束会抛出选择它的概率。下面的代码实际上忽略了这个问题,它只是强制执行了限制(换句话说,第二个数字<em>的概率不会</em>是为<code>prob_list</code>中的每个数字给定的概率)。</p>
<pre><code>import random
prob_list = [[1, 0.5], [2, 0.25], [3, 0.05], [4, 0.01], [5, 0.09], [6, 0.1]]
# create a list with the running total of the probabilities
acc = 0.0
acc_list = [acc]
for t in prob_list:
acc += t[1]
acc_list.append(acc)
TOLERANCE = .000001
def approx_eq(v1, v2):
return abs(v1-v2) <= TOLERANCE
def within(low, value, high):
""" Determine if low >= value <= high (approximately) """
return (value > low or approx_eq(low, value)) and \
(value < high or approx_eq(high, value))
def get_selection():
""" Find which weighted interval a random selection falls in """
interval = -1
rand = random.random()
for i in range(len(acc_list)-1):
if within(acc_list[i], rand, acc_list[i+1]):
interval = i
break
if interval == -1:
raise AssertionError('no interval for {:.6}'.format(rand))
return interval
def get_two_different_nums():
sel1 = get_selection()
sel2 = sel1
while sel2 == sel1:
sel2 = get_selection()
return prob_list[sel1][0], prob_list[sel2][0]
</code></pre>