首页 > 解决方案 > 2种方法,但仍然无法解决。蟒蛇2.7

问题描述

我努力了:

首先,我做了这样的代码

elif a_options == 2:
        a_update=raw_input("select a word to update:")
        a_renew_word = raw_input("the new word")
        if a_update in empt_list:
            empt_list[a_update]=a_renew_word
        else:
            print "sorry"
        # print a_list[a_options-1]

出现错误:

TypeError: list indices must be integers, not str

也试过:

elif a_options == 2:
    a_update=raw_input("select a word to update:")
    a_renew_word = raw_input("the new word")
    if a_update in empt_list:
        empt_list.index(a_update)=a_renew_word
    else:
        print "sorry"

另一个错误

SyntaxError: can't assign to function call

在这里你可以使用完整的代码,我尝试使用列表,因为我认为它最适合,但如果有任何其他方法我会接受它。任何想法,或者找到我试图搜索的问题,但我找不到任何解决方案,我在这里问你。

print "hello, welcome to"
a_list=["1. Add a new word","2. Update and existing word","3. Detele and existing word","4. Display a words definition"]
zero=0
empt_list=[]
empt_list_meaning=[]
def list_game():
    for i in a_list:
        print i
    a_options=input("Please select one of these options: ")
    if a_options== 1:
        a_newword=raw_input("What word you want to add? ")
        empt_list.append(a_newword)
        a_newword_meaning=raw_input("add the meaning of the word")
        empt_list_meaning.append(a_newword_meaning)
        # print a_list[a_options-1]
        print empt_list,a_newword,"added correctly"

    elif a_options == 2:
        a_update=raw_input("select a word to update:")
        a_renew_word = raw_input("the new word")
        if a_update in empt_list:
            empt_list.index(a_update)=a_renew_word
        else:
            print "sorry"
        # print a_list[a_options-1]

    elif a_options == 3:
        a_del_word=raw_input("selct the word you want to delete")
        for i in empt_list:
            if a_del_word in empt_list:
                empt_list.remove(a_del_word)
        # print a_list [a_options-1]


    elif a_options  == 4:
        for i in empt_list:
            print i
    print ("would you like to continue or exit?\n1.contine\n2.exit")
    now=input(">>> ")
    if now==1:
        list_game()
    else:
        print "arrivederchi"
list_game()

我不知道我还能做什么,感谢任何帮助。非常感谢你 umer selmani

标签: pythonpython-2.7

解决方案


用于.index()查找位置,然后分配给该位置的列表:

a_update=raw_input("select a word to update:")
a_renew_word = raw_input("the new word")
if a_update in empt_list:
    position = empt_list.index(a_update)
    empt_list[position] = a_renew_word
else:
    print "sorry"

这与@AChampion 建议的内容相同,但分为两行以使其更清晰。


推荐阅读