本文介绍了Python:当我们不需要重复的随机样本时如何使用随机样本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码
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?
推荐答案
来自文档 random.sample(MyList)
将为您提供列表项中的唯一答案.对于您要从中采样的MyList中的重复项,只需将其设置为 set .
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.
此外,您不需要每个样本都循环,您只需为其指定一个k参数,它将返回k个许多随机样本.所以整个代码可以写成:
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)
这篇关于Python:当我们不需要重复的随机样本时如何使用随机样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!