Trying to use sets for random selection, but the pop() method returns items in order

Mensanator mensanator at aol.com
Wed Jul 1 18:47:08 EDT 2009


On Jul 1, 5:29 pm, Mensanator <mensana... at aol.com> wrote:
> On Jul 1, 4:34 pm, Mario Garcia <Mario... at gmail.com> wrote:
>
>
>
>
>
> > Im trying to use sets for doing statistics from a data set.
> > I want to select, 70% random records from a List. I thougth set where
> > a good idea so I
> > tested this way:
>
> > c = set(range(1000))
> > for d in range(1000):
> >      print c.pop()
>
> > I was hoping to see a print out of random selected numbers from 1 to
> > 1000
> > but I got an ordered count from 1 to 1000.
> > I also tried using a dictionary, with keys from 1 to 10, and also got
> > the keys in order.
>
> > Im using:
> >  Python 2.5.2 |EPD 2.5.2001| (r252:60911, Aug  4 2008, 13:45:20)
> >  [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin
>
> > Examples in the documentation seem to work. But I cant make it.
> > Can some one, give me a hint on whats going on?
>
> Sets don't help. Try this:
>
> >>> import random
> >>> c = range(100)
> >>> c
>
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
> 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
> 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
> 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
> 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87,
> 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>
> >>> random.shuffle(c)
> >>> c
>
> [78, 62, 38, 54, 12, 48, 24, 20, 8, 14, 1, 69, 49, 92, 41, 64, 17, 35,
> 88, 40, 73, 45, 5, 84, 96, 90, 98, 57, 51, 75, 99, 13, 29, 4, 97, 77,
> 74, 56, 91, 95, 59, 79, 89, 19, 9, 42, 31, 85, 86, 23, 27, 50, 6, 21,
> 15, 80, 3, 30, 87, 82, 16, 63, 2, 55, 37, 33, 10, 61, 93, 72, 60, 67,
> 44, 65, 11, 70, 52, 58, 47, 18, 36, 66, 94, 28, 22, 68, 32, 76, 53,
> 25, 83, 34, 26, 71, 39, 43, 7, 46, 0, 81]
>
> >>> for d in c:

Oops! You don't want to iterate through c while popping it.
Your original for statement is what to use.

>
>         print c.pop(),
>
> 81 0 46 7 43 39 71 26 34 83 25 53 76 32 68 22 28 94 66 36 18 47 58 52
> 70 11 65 44 67 60 72 93 61 10 33 37 55 2 63 16 82 87 30 3 80 15 21 6
> 50 27
>
> Notice that the numbers are coming out in the exact reverse order
> of the list, because you used .pop() without an index number.
> But it's ok in _THIS_ example, because the list was randomly
> shuffled before popping.



More information about the Python-list mailing list