gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:08:14 28 4
gpt4 key购买 nike

我的代码

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 : How to use random sample when we don't need duplicates random sample,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44448860/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com