相关疑难解决方法(0)

random.choice的加权版本

我需要编写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 …
Run Code Online (Sandbox Code Playgroud)

python optimization

209
推荐指数
11
解决办法
14万
查看次数

加权选择简短

如果我在列表中有一组项目.我想根据另一个权重列表从该列表中进行选择.

例如我的收藏是['one', 'two', 'three']和权重[0.2, 0.3, 0.5],我希望这个方法在所有抽奖的大约一半中给我'三'.

最简单的方法是什么?

python numpy

46
推荐指数
4
解决办法
4万
查看次数

标签 统计

python ×2

numpy ×1

optimization ×1