LoginSignup
3
1

More than 5 years have passed since last update.

[Python3] 重み付きでランダムに値を取り出す

Last updated at Posted at 2018-12-25

Python 3.6 以降

random.choicesを使う

import random

target_dict = {"a": 3, "b": 4, "c": 2}
candidates = [*target_dict]
weights = [*target_dict.values()]

x = random.choices(candidates, weights=weights)[0]
print(x)

以前

bisectを使う

import random
import itertools
import bisect

target_dict = {"a": 3, "b": 4, "c": 2}
candidates = [*target_dict]
weights = [*target_dict.values()]

accumulation_weights = list(itertools.accumulate(weights))
x = candidates[bisect.bisect(accumulation_weights, random.random() * accumulation_weights[-1])]
print(x)
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1