Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!newsfeed.xs4all.nl!newsfeed3a.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.007 X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'compact': 0.09; 'orange': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'jan': 0.12; 'random': 0.14; '(0,': 0.16; 'bisect': 0.16; 'received:80.91.229.3': 0.16; 'received:plane.gmane.org': 0.16; 'reedy': 0.16; 'subject:sample': 0.16; 'wrote:': 0.18; '>>>': 0.22; 'import': 0.22; 'header:User-Agent:1': 0.23; 'header:X -Complaints-To:1': 0.27; 'header:In-Reply-To:1': 0.27; 'tim': 0.29; "i'm": 0.30; 'lines': 0.31; 'chase': 0.31; "i'd": 0.34; 'subject:with': 0.35; 'subject:?': 0.36; 'list': 0.37; 'expected': 0.38; 'apple': 0.38; 'form,': 0.38; 'needed': 0.38; 'to:addr :python-list': 0.38; 'pm,': 0.38; 'to:addr:python.org': 0.39; 'received:org': 0.40; 'received:173': 0.61; 'sample': 0.67; 'below.': 0.71; '50),': 0.84; 'received:fios.verizon.net': 0.84 X-Injected-Via-Gmane: http://gmane.org/ To: python-list@python.org From: Terry Reedy Subject: Re: random.sample with large weighted sample-sets? Date: Sun, 16 Feb 2014 04:12:22 -0500 References: <20140215224145.68c82eb4@bigbox.christie.dr> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Gmane-NNTP-Posting-Host: pool-173-75-254-207.phlapa.fios.verizon.net User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Thunderbird/24.3.0 In-Reply-To: <20140215224145.68c82eb4@bigbox.christie.dr> X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.15 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 45 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1392541984 news.xs4all.nl 2834 [2001:888:2000:d::a6]:52644 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:66521 On 2/15/2014 11:41 PM, Tim Chase wrote: > I'm not coming up with the right keywords to find what I'm hunting. > I'd like to randomly sample a modestly compact list with weighted > distributions, so I might have > > data = ( > ("apple", 20), > ("orange", 50), > ("grape", 30), > ) If you actually start with date in this form, write the few lines needed to produce the form below. import bisect import random data = [ (0, 'apple'), (20, 'orange'), (70, 'grape'), ] for i in range(10): r = random.randrange(0, 100) i = bisect.bisect(data, (r, 'zzzzz')) - 1 print(data[i][1]) >>> apple orange orange grape orange apple grape orange grape orange It is just coincidence that the sample has exactly the expected distribution. -- Terry Jan Reedy