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]
?
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.
unique() function. The unique() function is used to find the unique elements of an array. Returns the sorted unique elements of an array.
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With