implement random selection in Python

Boris Borcic bborcic at gmail.com
Fri Nov 16 11:03:56 CET 2007


Bruza wrote:
> No. That does not solve the problem. What I want is a function
> 
>   def randomPick(n, the_items):
> 
> which will return n DISTINCT items from "the_items" such that
> the n items returned are according to their probabilities specified
> in the (item, pro) elements inside "the_items".
> 
> If I understand correctly, both of the previous replies will output
> one item at a time independently, instead of returning n DISTINCT
> items at a time.
> 

from random import sample
randomPick = lambda n,its : sample(eval('+'.join('[%r]*%r'%p for p in its)),n)

hth :)




More information about the Python-list mailing list