我的密码

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 element_random[0] not in MyListRandom:
     MyListRandom.append(element_random[0])


如果我不希望重复样本,还有没有比这更好的方法了?

最佳答案

documentation random.sample(MyList)将为您提供列表项中的唯一答案。对于您从中采样的MyList中的重复项,只需将其设为set

同样,您不需要每个样本都循环,您只需为其指定一个k参数,它将返回k个许多随机样本。因此,整个代码可以写成:

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

关于python - Python:当我们不需要重复的随机样本时如何使用随机样本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44448860/

10-11 09:26
查看更多