pick randomly a certain fraction of numbers from a list

Steven Taschuk staschuk at telusplanet.net
Fri Feb 14 15:45:45 EST 2003


Quoth Yuval:
> Does anybody know a quick way of picking randomly x% of elements from a list. 
> e.g. If I have a list of 50 elements, how do I randomly choose 2% of it? 
> The trivial way would be to iterate with the random.choice() function. 
> Is there any better way? 

(You choose an interesting example, since 2% of a 50-item list is
a single item; thus one call to random.choice() is equivalent.  I
assume this is accidental.)

A somewhat costly alternative, in this example picking a random
third (almost) of a list:
	>>> import string
	>>> some_list = list(string.ascii_lowercase)
	>>> import random
	>>> indices = range(len(some_list))
	>>> random.shuffle(indices)
	>>> indices = indices[:len(indices)/3]
	>>> indices.sort()
	>>> print [some_list[i] for i in indices]
	['e', 'n', 'o', 'p', 't', 'v', 'w', 'x']
(But see help(random.shuffle) for limitations.)

I think iterating random.choice() is best.  (Or rather, writing a
function which does so.)

-- 
Steven Taschuk           | "We can't stop people from complaining, but
staschuk at telusplanet.net |  we can influence what they complain about."
                         |                                -- Tim Peters





More information about the Python-list mailing list