random.choice の重み付けバージョン 質問する

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 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

バージョン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描画された項目が置き換えられないように動作を変更することもできます。

おすすめ記事