使用limit Python从列表中选择随机变量

2024-09-27 17:32:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要为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来使用它的概率参数


Tags: 对象代码in列表ifobjectsisdef
3条回答

通过只向函数生成器添加object.remove()行,我成功地获得了我想要的解决方案

通过删除代码列表中附加的内容,可以消除重用

#generate random codes
def generator(code, objects):
    

    for i in range(len(code)):
        x = random.choices(objects)
        code[i] = x[0]
        
        #new line
        objects.remove(x[0])
        

这将从源中生成所有可能的3个唯一元素选择

import itertools
list(itertools.combinations('abcdefg',3))

[('a', 'b', 'c'),
 ('a', 'b', 'd'),
 ('a', 'b', 'e'),
 ('a', 'b', 'f'),
 ('a', 'b', 'g'),
 ('a', 'c', 'd'),
 ('a', 'c', 'e'),
 ('a', 'c', 'f'),
 ...
 ('d', 'f', 'g'),
 ('e', 'f', 'g')]

对于尺寸为5的,将是此列表

 list(itertools.combinations('abcdefg',5))

[('a', 'b', 'c', 'd', 'e'),
 ('a', 'b', 'c', 'd', 'f'),
 ('a', 'b', 'c', 'd', 'g'),
 ('a', 'b', 'c', 'e', 'f'),
 ('a', 'b', 'c', 'e', 'g'),
 ('a', 'b', 'c', 'f', 'g'),
 ('a', 'b', 'd', 'e', 'f'),
 ('a', 'b', 'd', 'e', 'g'),
 ('a', 'b', 'd', 'f', 'g'),
 ('a', 'b', 'e', 'f', 'g'),
 ('a', 'c', 'd', 'e', 'f'),
 ('a', 'c', 'd', 'e', 'g'),
 ('a', 'c', 'd', 'f', 'g'),
 ('a', 'c', 'e', 'f', 'g'),
 ('a', 'd', 'e', 'f', 'g'),
 ('b', 'c', 'd', 'e', 'f'),
 ('b', 'c', 'd', 'e', 'g'),
 ('b', 'c', 'd', 'f', 'g'),
 ('b', 'c', 'e', 'f', 'g'),
 ('b', 'd', 'e', 'f', 'g'),
 ('c', 'd', 'e', 'f', 'g')]

我会这样做:

from random import randrange as rr
Alphabet="abcdefghijklmnopqrstuvwxyz"
def generate(length):
    code=[]
    for _ in range(length):
         random_number=rr(0,len(Alphabet))
         if Alphabet[random_number]not in code:
             code.append(Alphabet[random_number])
    return code

这将从元组/列表/字符串(在我的示例中是字母表字符串)生成一个随机元素,并检查该元素是否已在代码中,如果未在代码中,则将其添加到代码中,代码的长度由参数确定

相关问题 更多 >

    热门问题