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

后端 未结 2 1970
佛祖请我去吃肉
佛祖请我去吃肉 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 07:59

    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)
    

提交回复
热议问题