Weighted "random" selection from list of lists
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Sun Oct 9 06:11:18 EDT 2005
On Sat, 08 Oct 2005 12:48:26 -0400, Jesse Noller wrote:
> Once main_list is populated, I want to build a sequence from items
> within the lists, "randomly" with a defined percentage of the sequence
> coming for the various lists. For example, if I want a 6 item
> sequence, I might want:
>
> 60% from list 1 (main_list[0])
> 30% from list 2 (main_list[1])
> 10% from list 3 (main_list[2])
If you are happy enough to match the percentages statistically rather than
exactly, simply do something like this:
pr = random.random()
if pr < 0.6:
list_num = 0
elif pr < 0.9:
list_num = 1
else:
list_num = 2
return random.choice(main_list[list_num])
or however you want to extract an item.
On average, this will mean 60% of the items will come from list1 etc, but
for small numbers of trials, you may have significant differences.
--
Steven.
More information about the Python-list
mailing list