关于根据元素的权重选择随机元素的 Python 算法

2014 年 12 月 8 日
 Livid

http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python/

Love this fast and elegant one.

class WeightedRandomGenerator(object):
    def __init__(self, weights):
        self.totals = []
        running_total = 0

        for w in weights:
            running_total += w
            self.totals.append(running_total)

    def next(self):
        rnd = random.random() * self.totals[-1]
        return bisect.bisect_right(self.totals, rnd)

    def __call__(self):
        return self.next()
3568 次点击
所在节点    Python
4 条回复
mengzhuo
2014 年 12 月 8 日
前段时间考察过这个算法,在总量小的情况下(<1000)
用Python自带的for 循环比 bisect效率高
koykoi
2014 年 12 月 8 日
Roulette Wheel
qiukun
2014 年 12 月 8 日
@mengzhuo 感人。。
efi
2014 年 12 月 9 日
numpy.random.choice(1, p=weights)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/152405

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX