代码之家  ›  专栏  ›  技术社区  ›  Colin

加权版本随机选择

  •  183
  • Colin  · 技术社区  · 14 年前

    我需要写一个加权版本的随机选择(列表中的每个元素被选中的概率不同)。这就是我想到的:

    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
    

    20 回复  |  直到 12 年前
        1
  •  4
  •   Ea Werner    4 年前

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