pick randomly a certain fraction of numbers from a list
Skip Montanaro
skip at pobox.com
Fri Feb 14 13:59:41 EST 2003
>> 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?
How about
random.shuffle(mylist)
picks = mylist[:int(len(mylist)*0.02)]
? Actually, since 2% of 50 is 1, this would work for your particular case:
random.shuffle(mylist)
picks = mylist[:1]
<wink>
Skip
More information about the Python-list
mailing list