python按概率生成指定数字_Python:选择具有关联概率的数字

I have a list of list which contains a series on numbers and there associated probabilities.

prob_list = [[1, 0.5], [2, 0.25], [3, 0.05], [4, 0.01], [5, 0.09], [6, 0.1]]

for example in prob_list[0] the number 1 has a probability of 0.5 associated with it. So you would expect 1 to show up 50% of the time.

How do I add weight to the numbers when I select them?

NOTE: the amount of numbers in the list can vary from 6 - 100

EDIT

In the list I have 6 numbers with their associated probabilities. I want to select two numbers based on their probability.

No number can be selected twice. If "2" is selected it can not be selected again.

解决方案

This might be what you're looking for. Extension to a solution in Generate random numbers with a given (numerical) distribution. Removes the selected item from the distribution, updates the probabilities and returns selected item, updated distribution. Not proven to work, but should give a good impression of the idea.

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