Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pick "x" number of unique numbers from a list in Python?

I need to pick out "x" number of non-repeating, random numbers out of a list. For example:

all_data = [1, 2, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 15, 15] 

How do I pick out a list like [2, 11, 15] and not [3, 8, 8]?

like image 635
George Avatar asked Jun 27 '11 14:06

George


People also ask

How do you get unique numbers from a list in Python?

Using Python's import numpy, the unique elements in the array are also obtained. In the first step convert the list to x=numpy. array(list) and then use numpy. unique(x) function to get the unique values from the list.

What does unique () do in Python?

unique() function. The unique() function is used to find the unique elements of an array. Returns the sorted unique elements of an array.

How do you count the number of unique values in an array in Python?

To count each unique element's number of occurrences in the numpy array, we can use the numpy. unique() function. It takes the array as an input argument and returns all the unique elements inside the array in ascending order.


2 Answers

That's exactly what random.sample() does.

>>> random.sample(range(1, 16), 3) [11, 10, 2] 

Edit: I'm almost certain this is not what you asked, but I was pushed to include this comment: If the population you want to take samples from contains duplicates, you have to remove them first:

population = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] population = set(population) samples = random.sample(population, 3) 
like image 122
Sven Marnach Avatar answered Oct 11 '22 07:10

Sven Marnach


Something like this:

all_data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] from random import shuffle shuffle(all_data) res = all_data[:3]# or any other number of items 

OR:

from random import sample number_of_items = 4 sample(all_data, number_of_items) 

If all_data could contains duplicate entries than modify your code to remove duplicates first and then use shuffle or sample:

all_data = list(set(all_data)) shuffle(all_data) res = all_data[:3]# or any other number of items 
like image 35
Artsiom Rudzenka Avatar answered Oct 11 '22 05:10

Artsiom Rudzenka