V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Livid
V2EX  ›  Python

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

  •  1
     
  •   Livid · 2014-12-08 17:32:56 +08:00 · 3133 次点击
    这是一个创建于 3427 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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()
    
    4 条回复    2014-12-09 01:11:16 +08:00
    mengzhuo
        1
    mengzhuo  
       2014-12-08 19:24:47 +08:00
    前段时间考察过这个算法,在总量小的情况下(<1000)
    用Python自带的for 循环比 bisect效率高
    koykoi
        2
    koykoi  
       2014-12-08 19:42:40 +08:00
    Roulette Wheel
    qiukun
        3
    qiukun  
       2014-12-08 22:41:34 +08:00
    @mengzhuo 感人。。
    efi
        4
    efi  
       2014-12-09 01:11:16 +08:00   ❤️ 1
    numpy.random.choice(1, p=weights)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2949 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 13:23 · PVG 21:23 · LAX 06:23 · JFK 09:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.