Python试图在数据库中保存唯一的值

2024-04-20 04:32:16 发布

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

大家好,我正在寻找的是生成一个随机值并插入到数据库中,在此之前,我尝试使用一个列表

问题是我需要生成一个随机代码,但要验证这个值是否不存在,因为随机代码可能会生成一个已经存在于数据库中的随机值

昨天我只是睡得很晚,但我没有做到

你们能帮个忙吗

import random
aleatorio = random.randrange(1,9)
print 'numero es igual a: %s' % aleatorio

    lista = [1,2,3,4]
    print lista

    if aleatorio in lista:
        print True


        while True:
            aleatorio = random.randrange(1,9)
            if aleatorio in lista:
                print 'este es el nuevo numero aleatorio %s' % aleatorio
                break

    else:
        print False

Tags: 代码inimport数据库true列表ifes
1条回答
网友
1楼 · 发布于 2024-04-20 04:32:16

与您的解释相比,您的代码有点混乱,但我将如何调整它,使其与您描述的内容相匹配

import random
aleatorio = random.randrange(1,9)
example_database = [1,2,3,4]
while aleatorio in example_database:
    print str(aleatorio) + " is already in database, please trying again"
    aleatorio = random.randrange(1,9)

print("chosen new number: "+str(aleatorio))
example_database.append(aleatorio)
if(set(example_database)==set(range(1,9))):
    print("No new numbers possible within range 1-9")

我不得不做出一些假设,比如lista是您的虚拟数据库。如果我误解了你的描述,请进一步询问

相关问题 更多 >