推荐学习书目
› 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
398.39D
556.49D
V2EX  ›  Python

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

  •  1
     
  •   Livid ·
    PRO
    · Dec 8, 2014 · 3927 views
    This topic created in 4320 days ago, the information mentioned may be changed or developed.

    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 replies  •  2014-12-09 01:11:16 +08:00
    mengzhuo
        1
    mengzhuo  
       Dec 8, 2014
    前段时间考察过这个算法,在总量小的情况下(<1000)
    用Python自带的for 循环比 bisect效率高
    koykoi
        2
    koykoi  
       Dec 8, 2014
    Roulette Wheel
    qiukun
        3
    qiukun  
       Dec 8, 2014
    @mengzhuo 感人。。
    efi
        4
    efi  
       Dec 9, 2014   ❤️ 1
    numpy.random.choice(1, p=weights)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2720 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 06:10 · PVG 14:10 · LAX 23:10 · JFK 02:10
    ♥ Do have faith in what you're doing.