gpt4 book ai didi

python - random.choice 的加权版本

转载 作者:太空宇宙 更新时间:2023-11-03 20:37:44 25 4
gpt4 key购买 nike

我需要编写 random.choice 的加权版本(列表中的每个元素都有不同的被选择概率)。这就是我想到的:

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

这个函数对我来说似乎过于复杂,而且丑陋。我希望这里的每个人都可以提供一些改进建议或其他方法。对我来说,效率并不像代码的整洁和可读性那么重要。

最佳答案

从 1.7.0 版本开始,NumPy 有 choice支持概率分布的函数。

from numpy.random import choice
draw = choice(list_of_candidates, number_of_items_to_pick,
p=probability_distribution)

请注意,probability_distribution 是与 list_of_candidates 顺序相同的序列。您还可以使用关键字 replace=False 更改行为,以便不替换绘制的项目。

关于python - random.choice 的加权版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57056690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com