使用这个answer 中的函数,您可以生成一个总和为y 的x 个随机数的列表。
遍历此列表中的项目,并从每个持有者的元素群体中做出许多随机选择(移除)。
或者举例:
# requires RandIntVec() & RandFloats() from linked answer
# whatever population you are choosing from, example letter
population = list('qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890')
# sizes (whatever you want)
num_of_holders = 7
total_elements = len(population)
# empty holder to put results in
element_holder = [[] for _ in xrange(num_of_holders)]
# distribute total_elements elements in randomly-sized portions among num_of_holders 'element holders'
random_portions_in_holder = RandIntVec(num_of_holders, total_elements, Distribution=RandFloats(num_of_holders))
# assign each portion of elements to each 'holder'
for h, portion in enumerate(random_portions_in_holder):
for p in range(portion):
index = random.randrange( len(population) )
element_holder[h].append(population.pop(index))
# display
print 'Randomly-portioned elements'
for h in element_holder:
print h
# verify
print '\nMatch desired result?'
print 'total_elements :', total_elements
print 'elements in holders :', sum([len(h) for h in element_holder])
print 'match :', total_elements == sum([len(h) for h in element_holder])
输出
Randomly-portioned elements
['M', 'N', 'f', 'V', 'v', 'h', 'i', 'H', '6', '5', 'j', '7', 'r']
['u', 'Z', 'C', 'I', 's', 'm', 'g', 'p', 'q', 'a', 'O', 'T', 'L']
['K', 'E', 'P', 'U']
['Y', 'D', 'A', 'l', 'J', 'R', 'b', 'c', 'z', 'F']
['0', '1', 'o', 'X', 'G', '4', 'W', '3', '2']
['d', 'Q']
['e', 'y', 'B', '8', 'x', 'k', 'w', 't', 'S', 'n', '9']
Match desired result?
total_elements : 62
elements in holders : 62
match : True
附注复制链接函数时出现了一些缩进错误,您可能需要更正它们。 elif Distribution.lower() == 'normal':下的代码需要un-缩进1级。我提交了一个经过编辑的版本(结束批准),所以根据您复制的时间,您可能需要也可能不需要编辑。