Python - 我只能用追加保存一件事?
Python - I can only save one thing with append?
这是我的代码。我无法在列表中保存超过 1 个东西,我不知道为什么。
程序的重点是保存单词(如"banana"),然后为其添加描述("yellow")。我正在使用 Python 2.7
word = []
desc = []
def main_list():
print "\nMenu for list \n"
print "1: Insert"
print "2: Lookup"
print "3: Exit program"
choice = input()
print "Choose alternative: ", choice
if choice == 1:
insert()
elif choice == 2:
look()
elif choice == 3:
return
else:
print "Error: not a valid choice"
def insert():
word.append(raw_input("Word to insert: "))
desc.append(raw_input ("Description of word: "))
main_list()
def look():
up = raw_input("Word to lookup: ")
i = 0
while up != word[i]:
i+1
print "Description of word: ", desc[i]
main_list()
一般情况下,您不应该使用两个列表来保存单词及其各自的描述。
这是使用字典的经典案例,当你有很多单词时,它也会帮助你,因为你不需要遍历所有条目来找到相应的描述。
words = {}
def main_list():
print "\nMenu for list \n"
print "1: Insert"
print "2: Lookup"
print "3: Exit program"
choice = input()
print "Choose alternative: ", choice
if choice == 1:
insert()
elif choice == 2:
look()
elif choice == 3:
return
else:
print "Error: not a valid choice"
def insert():
word = raw_input("Word to insert: ")
desc = raw_input ("Description of word: ")
words[word] = desc
main_list()
def look():
up = raw_input("Word to lookup: ")
print "Description of word: ", words.get(up, "Error: Word not found")
main_list()
您没有更新 i
的值。您正在调用 i+1
,它实际上并没有做任何事情(它只是评估 i + 1
并丢弃结果)。改为 i += 1
这似乎有效。
此外,当你有一个内置的数据结构时,这是一种相当奇怪的创建字典的方法 - 字典 ({}
)。
这是我的代码。我无法在列表中保存超过 1 个东西,我不知道为什么。
程序的重点是保存单词(如"banana"),然后为其添加描述("yellow")。我正在使用 Python 2.7
word = []
desc = []
def main_list():
print "\nMenu for list \n"
print "1: Insert"
print "2: Lookup"
print "3: Exit program"
choice = input()
print "Choose alternative: ", choice
if choice == 1:
insert()
elif choice == 2:
look()
elif choice == 3:
return
else:
print "Error: not a valid choice"
def insert():
word.append(raw_input("Word to insert: "))
desc.append(raw_input ("Description of word: "))
main_list()
def look():
up = raw_input("Word to lookup: ")
i = 0
while up != word[i]:
i+1
print "Description of word: ", desc[i]
main_list()
一般情况下,您不应该使用两个列表来保存单词及其各自的描述。
这是使用字典的经典案例,当你有很多单词时,它也会帮助你,因为你不需要遍历所有条目来找到相应的描述。
words = {}
def main_list():
print "\nMenu for list \n"
print "1: Insert"
print "2: Lookup"
print "3: Exit program"
choice = input()
print "Choose alternative: ", choice
if choice == 1:
insert()
elif choice == 2:
look()
elif choice == 3:
return
else:
print "Error: not a valid choice"
def insert():
word = raw_input("Word to insert: ")
desc = raw_input ("Description of word: ")
words[word] = desc
main_list()
def look():
up = raw_input("Word to lookup: ")
print "Description of word: ", words.get(up, "Error: Word not found")
main_list()
您没有更新 i
的值。您正在调用 i+1
,它实际上并没有做任何事情(它只是评估 i + 1
并丢弃结果)。改为 i += 1
这似乎有效。
此外,当你有一个内置的数据结构时,这是一种相当奇怪的创建字典的方法 - 字典 ({}
)。