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

后端 未结 2 1968
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 07:43

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(         


        
2条回答
  •  囚心锁ツ
    2021-01-22 08:17

    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)
    

提交回复
热议问题