Random selection

Hamilton, William whamil1 at entergy.com
Mon May 21 09:21:15 EDT 2007


> From: Tartifola
> Hi,
> I have a list with probabilities as elements
> 
> [p1,p2,p3]
> 
> with of course p1+p2+p3=1. I'd like to draw a
> random element from this list, based on the probabilities contained in
> the list itself, and return its index.
> 
> Any help on the best way to do that?
> Thanks

>>> ran = random.random()
>>> ran
0.70415952329234965
>>> for index, value in enumerate(x):
	if sum(x[0:index]) > ran:
		print index, ran
		break

	
2 0.704159523292

--
-Bill Hamilton



More information about the Python-list mailing list