随机选择的加权版本我需要编写随机选择的加权版本(列表中的每个元素被选中的概率不同)。这就是我想出来的:def weightedChoice(choices):
"""Like random.choice, but each element can have a different chance of
being selected.
choices can be any iterable containing iterables with two items each.
Technically, they can have more than two items, the rest will just be
ignored. The first item is the thing being chosen, the second item is
its weight. The weights can be any numeric values, what matters is the
relative differences between them.
"""
space = {}
current = 0
for choice, weight in choices:
if weight > 0:
space[current] = choice
current += weight
rand = random.uniform(0, current)
for key in sorted(space.keys() + [current]):
if rand < key:
return choice
choice = space[key]
return None这个功能对我来说太复杂了,太丑了。我希望在座的每一个人都能提出一些改进的建议,或者其他的方法。对我来说,效率并不像代码的整洁和可读性那么重要。
3 回答
蛊毒传说
TA贡献1895条经验 获得超3个赞
def weighted_choice(choices): total = sum(w for c, w in choices) r = random.uniform(0, total) upto = 0 for c, w in choices: if upto + w >= r: return c upto += w assert False, "Shouldn't get here"
添加回答
举报
0/150
提交
取消