Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-我只能用append保存一件事?_Python_List_Save_Append - Fatal编程技术网

Python-我只能用append保存一件事?

Python-我只能用append保存一件事?,python,list,save,append,Python,List,Save,Append,这是我的密码。我不能在列表中保存超过一件东西,我不知道为什么 程序的要点是保存单词(如“香蕉”),然后向其添加描述(“黄色”)。我正在使用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()

这是我的密码。我不能在列表中保存超过一件东西,我不知道为什么

程序的要点是保存单词(如“香蕉”),然后向其添加描述(“黄色”)。我正在使用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


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

您期望得到什么?您如何运行它?没有调用这些函数的主方法。如果我只插入单词“banana”和描述“yellow”,那么一切都可以正常工作,但是如果我还添加了其他东西,比如带有描述的“computer”,那么我只能查看“banana”。如果我用“计算机”看()什么也没发生,程序似乎永远都在加载。你认为Python2.7可能有问题吗?在你的代码中尝试
i+=1
,而不仅仅是
i+1
。没有分配任务,所以外观只是不断检查列表中的相同位置。@Kaiser您为什么使用递归调用?没有必要这样做。谢谢,这就是问题所在。您可以接受我的回答,并因此获得2个重复点的奖励!谢谢你的提示,我现在就试试。