【发布时间】:2020-12-03 17:57:25
【问题描述】:
我是 Python 新手,到目前为止,我已经学习了一些基本知识,例如数据类型、循环以及函数的工作原理。问题是我对数据库一无所知...
我想编写一个秘密圣诞老人代码来为我和我的朋友制作一个机器人。这个想法是,在您被邀请加入机器人后,您输入您的姓名和姓氏并被分配给一个人(我需要姓氏部分,因为有些人同名)。之后,分配的名称需要从初始的“目标”列表中删除,因此不会分配给其他任何人。
到目前为止,我已经完成了作业部分:
def appointer(name, surname):
template = "You are {}'s Secret Santa, congrats!"
targets = ['George Orwell', 'Vladimir Nabokov', 'Vladimir Sorokin']
if name == 'George' and surname == 'Orwell':
targets.remove('George Orwell')
print(template.format(random.choice(targets)))
elif name == 'Vladimir' and surname == 'Nabokov':
targets.remove('Vladimir Nabokov')
print(template.format(random.choice(targets)))
elif name == 'Vladimir' and surname == 'Sorokin':
targets.remove('Vladimir Sorokin')
print(template.format(random.choice(targets)))
print(targets)
else:
print('Wrong name, check again!')
(我需要单独的名称和目标列表,因为我的语言名称被拒绝。)
是的,这就是我已经走了多远!
所以下一步是让机器人记住分配的名称并将其从“目标”列表中删除,这样当下一个人使用机器人时,他或她就不会得到相同的名称。
我试图让分配的名称进入单独的列表和东西,但由于多个“if”循环,它不起作用。
所以我一直想知道有没有什么方法可以在不借助数据库的情况下完成这件事?
以下是更新:
通过内置字典记住分配的人的计划没有奏效,每次我运行代码时,这个字典都会重置为零。
然后我发现了一个非常有用的搁置模块。
下面是我在 Tom 的帮助下编写的代码:
import shelve
shelveFile = shelve.open('mydata')
import random
participants = [....]
template = "You're {}'s Secret Santa, congrats!"
def appointer(name, surname):
fullname = name + ' ' + surname
if fullname not in participants:
print("Wrong name, check again!)
return
if fullname in shelveFile.keys():
print("You already have your victim!")
return
options = [i for i in participants if i != fullname and i not in shelveFile.values()]
selection = random.choice(options)
shelveFile[fullname] = selection
print(template.format(selection))
if __name__ == '__main__':
appointer(name = input('Enter your name: ').lower().title(), surname = (input('Enter your surname:').lower().title()))
shelveFile.close()
Shelve 模块为您提供了一个内置数据库,每次运行代码时,您仍然可以记住所有分配的人员。
【问题讨论】:
标签: python python-3.x list memory