Python - 我只能通过追加保存一件事吗?

时间:2015-09-29 13:33:32

标签: python list save append

这是我的代码。我无法在列表中保存超过1件事,我不知道为什么。

程序的要点是保存单词(例如" banana"),然后为其添加说明("黄色")。我使用的是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()

2 个答案:

答案 0 :(得分:4)

您没有更新i的值。您正在调用i+1,它并没有真正做任何事情(它只是评估i + 1并丢弃结果)。相反,i += 1似乎有效。

此外,当你有一个内置的数据结构 - 字典({})时,创建字典是一种相当奇怪的方法。

答案 1 :(得分:0)

通常,您不应使用两个列表来保存单词及其各自的说明。

这是使用字典的经典案例,一旦你有很多单词,它也会帮助你,因为你不需要遍历所有条目来找到相应的描述。

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()