застрял при обновлении списка: индексы списка должны быть более ранними - PullRequest
0 голосов
/ 28 мая 2018

Пока что я написал этот код и застрял при обновлении списка.Я пробовал разные способы, в том числе и для цикла, но я не мог решить это.

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

Вот обратная связь:

Traceback (most recent call last):
  File "C:/Users/Umer Selmani/Desktop/newproject2018.py", line 44, in <module>
    list_game()
  File "C:/Users/Umer Selmani/Desktop/newproject2018.py", line 41, in list_game
    list_game()
  File "C:/Users/Umer Selmani/Desktop/newproject2018.py", line 22, in list_game
    empt_list[a_update]=a_renew_word
TypeError: list indices must be integers, not str

Process finished with exit code 1

Ответы [ 2 ]

0 голосов
/ 29 мая 2018

Ошибка, которую вы получаете из-за этой части кода,

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]

Поскольку индексы списка должны быть целыми числами, вы должны передать целое число в качестве индекса списка в приведенном ниже коде.Ниже приведен еще один способ сделать это:

if a_update in empt_list:
        #updated code
        lst_index=empt_list.index(a_update)
        empt_list[lst_index]=a_renew_word
    else:
        print "sorry"

Способ, который вы упомянули, мог бы работать, если empt_list был словарем, а не списком.Поскольку словари хранят данные в форме ключей, пары значений, поэтому они могут принимать как целые числа, так и строки в качестве ключей.

0 голосов
/ 28 мая 2018

Полагаю, именно этот бит вызывает проблемы.a_update - это строка, а не целое число.Список индексов должен быть целым числом.Попробуйте обновленный код ниже:

elif a_options == 2:
    a_update=raw_input("select a word to update:")
    # Note a_update is a string that user enters
    a_renew_word = raw_input("the new word")
    if a_update in empt_list:
        # This bit is changed from empt_list[a_update] to...
        empt_list.index(a_update)=a_renew_word
    else:
        print "sorry"
    # print a_list[a_options-1]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...