有不同的机会选择一个名字

时间:2014-08-09 13:12:41

标签: python random

我正在编写一个工作程序,我从.txt文档中提取两个名字。我已经编写了一个程序来获取名称但我需要更改它,以便我可以给每个名称一个被选中的概率。这个概率会随着我的审核而改变。我怎么能用Python做到这一点?我附上了我迄今为止所做的代码,但我不知道如何让它有不同的概率。

import os
os.chdir('C:/Users/Lance/Documents/Teams')
with open('San_Diego.txt') as taf:
    data = taf.readline()
San_Diego = data.strip().split(',')
with open('OCIE.txt') as oaf:
    data = oaf.readline()
OCIE = data.strip().split(',')   
def picker(seq):
    from functools import partial
    from random import choice
    return partial(choice, seq)
team_picker = picker(San_Diego)
print([team_picker() for c in range(2)])
team_picker = picker(OCIE)
print([team_picker() for c in range(2)])

1 个答案:

答案 0 :(得分:5)

鉴于两个名称 jack jill ,各自的权重分别为0.25和0.75,这是一个使用numpy包来选择5的解决方案加权随机名称:

import numpy

names = ['jack', 'jill']
weights = [0.25, 0.75]
bins = numpy.add.accumulate(weights)
selected_indexes = numpy.digitize(numpy.random.random_sample(5), bins)

print numpy.array(names)[selected_indexes]

执行这三次,我得到以下输出:

['jill' 'jack' 'jill' 'jill' 'jill']
['jack' 'jill' 'jill' 'jack' 'jill']
['jill' 'jill' 'jill' 'jill' 'jill']