pick randomly a certain fraction of numbers from a list

Gerrit Holl gerrit at nl.linux.org
Fri Feb 14 14:14:48 EST 2003


Skip Montanaro schreef op vrijdag 14 februari om 20:01:06 +0000:
>     >> 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)]

Although sometimes, this is faster:
 29 >>> def pick2(l, n):
 29 ...  i = len(l)
 29 ...  return [l.pop(random.randint(0, i-e-1)) for e in xrange(n)]

When l is large and n is small, pick2 is faster:
 35 >>> profile.run("pick1(range(1e5), 5)")
         4 function calls in 0.910 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.870    0.870 <stdin>:1(pick1)
        1    0.040    0.040    0.910    0.910 <string>:1(?)
        1    0.000    0.000    0.910    0.910 profile:0(pick1(range(1e5), 5))
        0    0.000             0.000          profile:0(profiler)
        1    0.870    0.870    0.870    0.870 random.py:191(shuffle)


 36 >>> profile.run("pick2(range(1e5), 5)")
         13 function calls in 0.080 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.010    0.010    0.010    0.010 <stdin>:1(pick2)
        1    0.070    0.070    0.080    0.080 <string>:1(?)
        1    0.000    0.000    0.080    0.080 profile:0(pick2(range(1e5), 5))
        0    0.000             0.000          profile:0(profiler)
        5    0.000    0.000    0.000    0.000 random.py:128(randrange)
        5    0.000    0.000    0.000    0.000 random.py:179(randint)

This is, of course, because shuffling a large list is overkill when one
needs only a few elements.

yours,
Gerrit.

-- 
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/





More information about the Python-list mailing list