我需要为3个不同的对象生成唯一的随机列表,每个对象可以在每个lis上出现一次,每个代码的固定长度为5
import random
#generate random codes
def generator(code, objects):
for i in range(len(code)):
x = random.choices(objects)
code[i] = x[0]
#Check if code is unique
def isSame(code, list):
if code not in list:
return False
else:
return True
#If code is unique, append it to the codeList and increase counter by 1
codeCount = 0
def listAppend(code, list):
if isSame(code,list) == True:
print('This code is not unique')
else:
list.append(code)
global codeCount
codeCount += 1
if __name__ == '__main__':
codeList = []
desiredCount = 12
while codeCount != desiredCount:
code = [None]*5
objects = ['a','b','c','d','e','f','g']
generator(code, objects)
listAppend(code,codeList)
print(codeList)
这给了我随机的唯一列表,但我想不出如何使每个对象在每个唯一列表中只出现一次
例如。['a','g','g','a','e']=>;'“g”和“a”重复了两次,我只需要它们出现一次。比如,['a','b','c','d','e']
有人能想出一个好办法吗?谢谢
编辑:每个代码的固定长度必须为5。我还使用random.choices来使用它的概率参数
通过只向函数生成器添加object.remove()行,我成功地获得了我想要的解决方案
通过删除代码列表中附加的内容,可以消除重用
这将从源中生成所有可能的3个唯一元素选择
对于尺寸为5的,将是此列表
我会这样做:
这将从元组/列表/字符串(在我的示例中是字母表字符串)生成一个随机元素,并检查该元素是否已在代码中,如果未在代码中,则将其添加到代码中,代码的长度由参数确定
相关问题 更多 >
编程相关推荐