Pick items from list with probability based upon property of list member ?

Nobody nobody at nowhere.com
Sun Jun 20 09:48:09 EDT 2010


On Sun, 20 Jun 2010 03:19:55 -0700, southof40 wrote:

> I want to select an object from the list with a probability of : cars
> 0.7, bikes 0.3, trucks 0.1.
> 
> I've currently implemented this by creating another list in which each
> car object from the original list appears 7 times, each bike 3 times
> and each truck once. I then pick at random from that list.
> 
> This works but seems very clunky to me. Can anyone suggest a better
> data structure which would support the 'weighted randomness' I'm
> after ?

Calculate the cumulative probabilities and perform a binary search (e.g.
using the bisect module).




More information about the Python-list mailing list