如何解决在 python 中不使用 tupler 或字典创建词汇表
def glossary():
print("Menu for glossary\n Type 1 to insert a new word\n Type 2 to lookup a word\n Type 3 to exit\n")
answer = input("Write your answer here: ")
if answer == "1":
Insert()
elif answer == "2":
lookup()
elif answer == "3":
return
else:
print("\nTry again!\n")
glossary()
def insert():
words = []
descriptions = []
word = input("Type the word you want to add: ")
words.append(word)
description = input("Descripe the word you want to add: ")
descriptions.append(description)
return words,descriptions
def lookup():
words = insert()
descriptions = insert()
print(words,"\n",descriptions)
嗨,我正在尝试在不使用元组或字典的情况下在 python 中创建词汇表。词汇表应该由两个字符串列表组成。一个是词的列表,另一个是该词的描述。用户将获得两个选项,插入带有描述的新词或查找词汇表中已有词的描述。操作插入和查找应该在单独的函数中,因为它在我的代码中。我遇到的问题是,当我运行程序并选择 1 插入一个单词时,一切都很顺利,并且该单词及其描述被插入到列表中。但是当菜单返回并且我选择 2 来查找我刚刚插入的单词时,当我尝试将列表传输到查找功能时遇到了问题。因为当我尝试从插入函数中获取返回值时,它会再次调用该函数。所以我的问题基本上是将编辑过的列表从插入函数转移到查找函数,而无需再次运行插入函数。如您所见,查找功能还远未完成,但我遇到了这个问题。
解决方法
这段代码有很多问题,如果我没有正确解释它们,我深表歉意,我对 python 世界还是比较陌生。
目前在您的插入功能中没有存储“单词”和“描述”列表的中央集线器。当您调用该函数时,您实际上并未为其分配任何变量。每次调用该函数时,都会用空列表覆盖添加到这些列表中的任何内容。此外,通过在查找函数中调用函数插入,您并没有调用您想要的值。您正在运行整个函数,这不是您想要发生的。
我将首先更改您的词汇表功能,使其充当程序的中心枢纽。请注意,列表“单词”和“描述”位于 while 循环之外,因此它们可以保留信息。我还更改了“if answer ==“3””以打破循环而不是不返回任何内容。最后,在调用 insert 和 lookup 时,我为它们提供了在函数中使用的变量。
def glossary():
words = []
descriptions = []
while True:
print("\nMenu for glossary\n Type 1 to insert a new word.\n Type 2 to lookup a word.\n Type 3 to exit.\n")
answer = input("Write your answer here: ")
if answer == "1":
insert(words,descriptions)
elif answer == "2":
lookup(words,descriptions)
elif answer == "3":
break
else:
print("\nTry again!\n")
函数插入看起来也有点不同,如前所述,从函数中删除了“单词”和“描述”列表。此外,当函数被调用时,它会被赋予变量来使用。这个函数没有 return 语句,据我所知这很好。如果你真的想要一个,可以换一个。
def insert(words,descriptions):
word = input("Type the word you want to add: ")
words.append(word)
description = input("Descripe the word you want to add: ")
descriptions.append(description)
最后是查找功能。它看起来非常不同。它不再调用其中的另一个函数,它主要充当打印列表的函数。
def lookup(words,descriptions):
print('\n')
print(*words,sep = ",")
print(*descriptions,")
当然,我们调用函数词汇表来运行程序。
glossary()
完整代码:
def glossary():
words = []
descriptions = []
while True:
print("\nMenu for glossary\n Type 1 to insert a new word.\n Type 2 to lookup a word.\n Type 3 to exit.\n")
answer = input("Write your answer here: ")
if answer == "1":
insert(words,descriptions)
elif answer == "3":
break
else:
print("\nTry again!\n")
def insert(words,descriptions):
word = input("Type the word you want to add: ")
words.append(word)
description = input("Descripe the word you want to add: ")
descriptions.append(description)
def lookup(words,")
glossary()
这是一个非常奇怪的问题,如果我没有正确理解您的要求,我深表歉意。为了我的理智,我还更改了一些打印输出。我不知道你想用这段代码做什么,但我认为一个有趣的方法是通过索引访问“单词”和“描述”的特定部分的值以进行编辑或打印。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。