這是一個簡單的變種,將做你想做的。需要注意的是幾乎肯定多更有效的方式來做到這一點,因爲這是目前爲O(n^2)在運行時間和使用N * m,其中ñ輸入人口規模和最大內存m是平均重量,因爲它建立了一個列表,每個重量具有一個輸入列表值的副本。
import random
import itertools
def random_weighted_shuffle(input_population):
'''
:param input_population: {name:weight}, where weight is the 'number of chances' that this particular name will be drawn
'''
out_list = []
while input_population:
lotto_list = list(itertools.chain.from_iterable([name]*weight for name, weight in input_population.iteritems()))
selection = lotto_list[random.randint(0,len(lotto_list)-1)]
del input_population[selection]
out_list.append(selection)
return out_list
一個非常重要的注意事項:由於寫的,這種方法是破壞性的輸入字典。
用法:
>>> random_weighted_shuffle({'a':10,'b':2,'c':5})
['a', 'b', 'c']
>>> random_weighted_shuffle({'a':10,'b':2,'c':5})
['a', 'c', 'b']
>>> random_weighted_shuffle({'a':10,'b':2,'c':5})
['b', 'c', 'a']
>>> random_weighted_shuffle({'a':10,'b':2,'c':5})
['c', 'a', 'b']
>>> random_weighted_shuffle({'a':10,'b':2,'c':5})
['a', 'c', 'b']
你所說的「挑」是什麼意思?你只是在洗牌而不是選擇一個項目。 http://stackoverflow.com/questions/14992521/python-weighted-random可能有幫助嗎? – geoffspear 2014-10-16 17:04:00
可能會更容易添加額外的名稱,你想多出來的名字 – 2014-10-16 17:05:34
另請參見http://programmers.stackexchange.com/questions/233541/how-to-implement-a-weighted-shuffle – aruisdante 2014-10-16 17:06:28