Weighted "random" selection from list of lists

Scott David Daniels scott.daniels at acm.org
Sat Oct 8 16:22:56 EDT 2005


Jesse Noller wrote:
<paraphrased>
> 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:
> 60% from list 1 (main_list[0]), 30% from list 2 (main_list[1]), 10% from list 3 (main_list[2])


import bisect, random
main_list = [['a', 'b', 'c'],
              ['dog', 'cat', 'panda'],
              ['blue', 'red', 'green']]
weights = [60, 30, 10]

cumulative = []
total = 0
for index, value in enumerate(weights):
     total += value
     cumulative.append(total)

for i in range(20):
     score = random.random() * total
     index = bisect.bisect(cumulative, score)
     print random.choice(main_list[index]),


-- 
-Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list