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

时间:2017-03-20 20:03:03

标签: python loops while-loop

大家好,我正在寻找生成随机值并插入数据库的内容,在此之前,我正在尝试使用列表。

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

昨天我只是睡得很晚但我没有实现。

你们能帮忙吗?

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

1 个答案:

答案 0 :(得分:0)

与您的解释相比,您的代码有点令人困惑,但是这里是我如何调整它以使其符合您所描述的内容。

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是你假装的数据库。如果我误解了你的描述,请进一步询问。