大家好 我正在寻找的是生成一个随机值并插入数据库,在此之前,我正在尝试使用列表来执行此操作。
问题是我需要生成一个随机代码,但验证此值是否存在,因为随机可能会生成数据库中已有的随机值。
昨天我只是睡得很晚,但我没有实现。
你们能帮忙吗?
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
与您的解释相比,您的代码有点令人困惑,但是这是我如何调整它,以便它与您似乎描述的内容相匹配。
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
是你的假装数据库。请进一步询问我是否误解了您的描述。