Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get random sample from list while maintaining ordering of items?

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...

like image 274
Yochai Timmer Avatar asked Jun 26 '11 08:06

Yochai Timmer


People also ask

How do you get a random sample from a list in Python?

In Python, you can randomly sample elements from a list with choice() , sample() , and choices() of the random module. These functions can also be applied to a string and tuple. choice() returns one random element, and sample() and choices() return a list of multiple random elements.

Does random sample return a list?

sample() function. sample() is an inbuilt function of random module in Python that returns a particular length list of items chosen from the sequence i.e. list, tuple, string or set.

How do I randomly select multiple items from a list in Python?

You can use random. randint() and random. randrange() to generate the random numbers, but it can repeat the numbers.

What is random sample Python?

Python Random sample() Method The sample() method returns a list with a randomly selection of a specified number of items from a sequnce. Note: This method does not change the original sequence.


1 Answers

Following code will generate a random sample of size 4:

import random  sample_size = 4 sorted_sample = [     mylist[i] for i in sorted(random.sample(range(len(mylist)), sample_size)) ] 

(note: with Python 2, better use xrange instead of range)

Explanation

random.sample(range(len(mylist)), sample_size) 

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

These indices then get sorted to preserve the ordering of elements in the original list.

Finally, the list comprehension pulls out the actual elements from the original list, given the sampled indices.

like image 69
mhyfritz Avatar answered Sep 29 '22 12:09

mhyfritz