重み付け乱択は、2段階で改良できます。 まず、1段階目として、リストを1回走査するだけで(重みの合計値を求めながら) 乱択することができます。 import random def random_weight_choice(L): choice = None total = 0 for item, p in L: total += p if random.random() * total < p: choice = item return choice def test_random_weight_choice(): from collections import defaultdict X = [('A', 3), ('B', 2), ('C', 5)] count = defaultdict(int) for _ in xrange(100000): item = random_weig
![重み付け乱択 - Qiita](https://cdn-ak-scissors.b.st-hatena.com/image/square/1ccd555475fe4a294fc63339aa3bd90300d7c75e/height=288;version=1;width=512/https%3A%2F%2Fqiita-user-contents.imgix.net%2Fhttps%253A%252F%252Fcdn.qiita.com%252Fassets%252Fpublic%252Farticle-ogp-background-9f5428127621718a910c8b63951390ad.png%3Fixlib%3Drb-4.0.0%26w%3D1200%26mark64%3DaHR0cHM6Ly9xaWl0YS11c2VyLWNvbnRlbnRzLmltZ2l4Lm5ldC9-dGV4dD9peGxpYj1yYi00LjAuMCZ3PTkxNiZoPTMzNiZ0eHQ9JUU5JTg3JThEJUUzJTgxJUJGJUU0JUJCJTk4JUUzJTgxJTkxJUU0JUI5JUIxJUU2JThBJTlFJnR4dC1jb2xvcj0lMjMyMTIxMjEmdHh0LWZvbnQ9SGlyYWdpbm8lMjBTYW5zJTIwVzYmdHh0LXNpemU9NTYmdHh0LWNsaXA9ZWxsaXBzaXMmdHh0LWFsaWduPWxlZnQlMkN0b3Amcz01NGNiZjY1OTA5ZWRlYTJlNzIwY2JlZjE2N2E0YmEwMw%26mark-x%3D142%26mark-y%3D112%26blend64%3DaHR0cHM6Ly9xaWl0YS11c2VyLWNvbnRlbnRzLmltZ2l4Lm5ldC9-dGV4dD9peGxpYj1yYi00LjAuMCZ3PTYxNiZ0eHQ9JTQwbWV0aGFuZSZ0eHQtY29sb3I9JTIzMjEyMTIxJnR4dC1mb250PUhpcmFnaW5vJTIwU2FucyUyMFc2JnR4dC1zaXplPTM2JnR4dC1hbGlnbj1sZWZ0JTJDdG9wJnM9ODdhZTg0ZjIxMWY4MDA4ZjUxYzNhZmE5NDJhM2I4ZTk%26blend-x%3D142%26blend-y%3D491%26blend-mode%3Dnormal%26s%3Db8a8a1ff5ca5d26912173d2eb915a815)