相关疑难解决方法(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万
查看次数

随机Python字典键,按值加权

我有一个字典,其中每个键都有一个可变长度列表,例如:

d = {
 'a': [1, 3, 2],
 'b': [6],
 'c': [0, 0]
}
Run Code Online (Sandbox Code Playgroud)

是否有一种干净的方法来获取随机字典键,按其值的长度加权? random.choice(d.keys())将对键进行相同的加权,但在上面的情况下,我希望'a'大约一半的时间返回.

python random dictionary

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

标签 统计

python ×2

dictionary ×1

optimization ×1

random ×1