Yochai Timmer - 5 months ago 53

Python Question

I have a sorted list, let say: (its not really just numbers, its a list of objects that are sorted with a complicated time consuming algorithm)

`mylist = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ,9 , 10 ]`

Is there some python function that will give me N of the items, but will keep the order?

Example:

`randomList = getRandom(mylist,4)`

# randomList = [ 3 , 6 ,7 , 9 ]

randomList = getRandom(mylist,4)

# randomList = [ 1 , 2 , 4 , 8 ]

etc...

Answer

Following code will generate a random sample of size 4.

```
rand_smpl = [ mylist[i] for i in sorted(random.sample(xrange(len(mylist)), 4)) ]
```

Explanation:

```
random.sample(xrange(len(mylist)), sample_size)
```

generates a random sample of the *indices* of the original list.

This sample then gets sorted to preserve the ordering of elements in the original list.

Finally, the list comprehension pulls out the elements from the original list, given the sampled indices, and constructs the final sample (of actual elements).