Aidento
Aidento

Reputation: 35

Python : How to use random sample when we don't need duplicates random sample

My Code

import random

MyList = [[1,2,3,4,5,6,7,8],[a,s,d,f,g,h,h],[q,w,e,r,t,y]]
MyListRandom = []
random_number = 5
i=0
while True:
     random_list = randint(0,len(MyList))
     element_random = random.sample(MyList[random_list], 1)
     if element_random[0] not in MyListRandom:
     i = i+1
     MyListRandom.append(element_random[0])
else:
    continue 
if(i>=random_number):
    break

if I don't want to use this code to check it

 if element_random[0] not in MyListRandom:
     MyListRandom.append(element_random[0])

Is there a better way more than this if i don't want a duplicates sample?

Upvotes: 2

Views: 1304

Answers (2)

OldGeeksGuide
OldGeeksGuide

Reputation: 2928

If I understand your question understand correctly, you just want a randomized version of your original list, also eliminating any duplicates in your original list. If that's correct you can use set and shuffle:

MyListRandom = list(set(MyList))
random.shuffle(MyListRandom)

If you're not worried about duplicates in your original list, just trying to workaround the possible duplicates introduced by sample, then this would work:

MyListRandom = MyList[:]   # to make a copy
random.shuffle(MyListRandom)

Upvotes: 1

umutto
umutto

Reputation: 7700

From the documentation random.sample(MyList) will give you unique answers from the list's items already. For duplicates in MyList you sample from, you can just make it a set.

Also you don't need the loop for every sample, you can just give it a k argument and it will return k many random samples. So the whole code can be written as:

# I have flatten the whole list into one list 
element_random = random.sample(set([item for sublist in MyList for item in sublist]), 5)

Upvotes: 1

Related Questions