all

random.choice 的加权版本

发布于 2022-04-11 13:24:57

我需要编写一个加权版本的 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

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

关注者
0
被浏览
20
1 个回答
  • 面试哥
    面试哥 2022-04-11
    为面试而生,有面试问题,就找面试哥。

    从 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来更改行为,以便绘制的项目不会被替换。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看