簡體   English   中英

為什么我得到 IndexError: list assignment index out of range

[英]why do i get the IndexError: list assignment index out of range

我想知道一封信在列表中的位置以及它出現了多少次。 當我得到這些職位時,我想用列表right_user_input替換相同的職位。

但是每當我嘗試這樣做時,它都會返回此錯誤IndexError: list assignment index out of range.

誰能告訴這是為什么?

import random
import re
from words import words

# the word that the user needs to guess
the_guess_word = random.choice(words)

n = 0
# puts the random picked word in a list
l_guess = list(the_guess_word)
box = l_guess

# somethings are not yet finished
print("Welcome To The Guessing Game . \n You get 6 Guesses . The Words Are In Dutch But There Is 1 English Word . "
  "\n If You Would Want To Try Again You Can Press (ctrl+Z)"
  f"\n \n Your Word Has {len(the_guess_word)} letters ")

class hangman:
    t = len(box)
    right_user_input = []

    # should create the amount of letters in the word
    right_user_input.append(t * ".")


    while True:
        # the user guesses the letter
        user_guess = input("guess the word : ")

        # if user guesses it wrong 6 times he or she loses
        if n >= 6 :
            print("you lose!")
            print(f'\n the word was {the_guess_word}')
            break

            # loops over until user gets it right or loses
        if user_guess not in the_guess_word:
                print("\n wrong guess try again ")
                n += 1

        # when user gets it right the list with the dots gets replaced by the guessed word of the user
        if user_guess in the_guess_word :
            print("you got it right")

            # finds the position of the guessed word in the to be guessed the word
            for m in re.finditer(user_guess, the_guess_word):
                right_user_input[m.end()] = user_guess

                print(right_user_input)

# this the error that i get
# i tried searching around but usually people have empty strings in my case that is not the issue .
# and the value in the right_user_input is len(the_guess_word) * "."

   Traceback (most recent call last):
  File "C:/Users/Admin/PycharmProjects/hangman/main.py", line 16, in <module>
    class hangman:
  File "C:/Users/Admin/PycharmProjects/hangman/main.py", line 38, in hangman
    right_user_input[m.end()] = user_guess
IndexError: list assignment index out of range

問題是您沒有正確設置right_user_input right_user_input.append(t * ".")只是使變量等於 t 個點的單個字符串 ( ["....."] ) 而不是 1 個點的 t 個字符串 ( [".", ".", ".", ".", "."] )。

要解決此問題,請以這種方式聲明變量:

right_user_input = ["." for i in range(len(the_guess_word))] right_user_input = ["." for i in range(len(the_guess_word))]

此外,將right_user_input[m.end()] = user_guess

right_user_input[m.end()-1] = user_guess ,因為 arrays 從 0 開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM