Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Sample with remove from List

I have data in a list like:

L = [(3,4,5),(1,4,5),(1,2,3),(1,2,3)]

I need to sample randomly a size of 2 so I wanted to use:

import random
t1 = random.sample(set(L),2)

Now T1 is a List of the randomly pulled values, But i wanted to remove those randomly pulled from our initial list from our initial list. I could do a linear for loop but for the task I'm trying to do this for a larger list. so the Run time would take for ever!

Any suggestions on how to go about this?

like image 458
Conor Avatar asked May 10 '13 07:05

Conor


People also ask

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

Use the random. choices() function to select multiple random items from a sequence with repetition. For example, You have a list of names, and you want to choose random four names from it, and it's okay for you if one of the names repeats.


2 Answers

t1 = [L.pop(random.randrange(len(L))) for _ in xrange(2)]

doesn't change the order of the remaining elements in L.

like image 82
eumiro Avatar answered Oct 07 '22 17:10

eumiro


One option is to shufle the list and then pop the first two elements.

import random
L = [(3,4,5),(1,4,5),(1,2,3),(1,2,3)]
random.shuffle(L)
t1 = L[0:2]
like image 24
jvallver Avatar answered Oct 07 '22 17:10

jvallver