繁体   English   中英

如何修复 Python 上的“IndexError: list index out of range”

[英]How to fix "IndexError: list index out of range" on Python

我正在尝试调试我为作业编写的一些代码,但无论我尝试什么,我都无法修复发生的错误。

我试过从我的朋友那里复制一些代码,但无论我尝试什么代码,我都会收到这个错误。

#NEA 2019 DICE GAME
from time import sleep as wait
from random import randint as rand
#Here I have imported my modules that I will use later on.

Check1 = 0
#Here I create a check variable, for use in the usernames section.

print("welcome to Dice Game!")
print("Main Menu: \n 1. Play Game \n 2. Register User \n 3. View Leaderboard \n 4. Quit Game")
MenuChoice = int(input("Please enter the number of the option you would like to choose."))
#Nice greeting for the user, and a menu.

elif MenuChoice == 1:
    while Check1 == 0:
        Namae = input("Player One, Please enter your username: \n")
        with open('Usernames.txt') as openfile:
            if Namae in openfile.read():
                print("Username",Namae, "Valid!")
                Check1 = 1
                Pass = input("Please enter the passkey:")
                if Pass == 'VN467' or Pass == 'Backdoor':
                #This 'if' statement allows the user to log in using a universal passkey, or allows an administrator to log in using a backdoor.
                    print("User Authenticated!")
                else:
                    print("Invalid Passkey!")
            else:
                print("Username",Namae, "Invalid!")
    #This block allows a user to log in as player 1.


    while Check1 == 1:
        Namae2 = input("Player Two, Please enter your username: \n")
        if Namae == Namae2:
            print("Both players can't have the same username!")
            Namae2 = ''
        with open('Usernames.txt') as openfile:
            if Namae2 in openfile.read():
                print("Username", Namae2, "Valid!")
                Check1 = 0
                Pass = input("Please enter the passkey:")
                if Pass == 'VN467' or Pass == 'Backdoor':
                    print("User Authenticated!")
                else:
                    print("Invalid Passkey!")
            else:
                print("Username", Namae2, "Invalid!")
    #This block allows a user to log in as player 2.
    P1total = 0
    P2total = 0

    for i in range (1,5):
        print("Game starting!")
        wait(1)
        print("ROUND", i)
        print(Namae, " Press 'Enter' to roll")
        #This gives the player a message box to allow them to roll.
        Roll1 = rand(1,6)
        Roll2 = rand(1,6)
        #This is the command to roll the dice.
        if Roll1 == Roll2:
            print("Double! You get an extra dice!")
            Roll3 = rand(1,6)
            #This gives the player another dice if they roll a double.
        else:
            Roll3 = 0
            #This sets the value of Roll3 to zero, to prevent a NameError later on.

        TempTotal = Roll1 + Roll2 + Roll3
        print("The total of the dice is", TempTotal)
        #These lines add together all of the dice.
        if TempTotal%2 == 0:
            print("Even total! +10 points!")
            TempTotal = TempTotal + 10
            #These lines check if the dice total is even, then adds 10 if it is.
        else:
            print("Odd total! -5 points")
            TempTotal = TempTotal - 5
            #These lines check if the dice total is odd, then subtracts 5 if it is.
        P1total = P1total + TempTotal
        if P1total < 0:
            P1total = 0
            #These lines make sure that the total cannot go below 0, and sets it to 0 if it does.
        print(Namae, "Your total is", P1total)
        #This prints the current total for player 1.
        print(Namae2," Press 'OK' to roll")
        Roll1 = rand(1,6)
        Roll2 = rand(1,6)
        #This rolls the two dice.
        if Roll1 == Roll2:
            print("Double! You get an extra dice!")
            Roll3 = rand(1,6)
            #This adds another dice if the player rolls a double.
        else:
            Roll3 = 0
            #This sets Roll3 to 0 to prevent a NameError later on in the code.
        TempTotal = Roll1 + Roll2 + Roll3
        #This adds up the dice to create a total.
        print("The total of the dice is", TempTotal)
        #This tells the player what the dice rolled.
        if TempTotal%2 == 0:
            print("Even total! +10 points!")
            TempTotal = TempTotal + 10
            #This adds 10 points to the total if they roll an even number.
        else:
            print("Odd total! -5 points")
            TempTotal = TempTotal - 5
            #This takes away 5 points from the total if they roll an odd number.
        P2total = P2total + TempTotal
        if P2total < 0:
            P2total = 0
        print(Namae2, "Your total is", P2total)
    if P1total == P2total:
        print("There is a draw! \n Both players will roll 1 die.")
        Roll1 = rand(1,6)
        Roll2 = rand(1,6)
        #This makes it so that there cannot be a draw
        print("Player 1 rolls a", Roll1, "\n Player 2 rolls a",Roll2)
        while Roll1 == Roll2:
            print("Another Draw!")
            Roll1 = rand(1,6)
            Roll2 = rand(1,6)
            #This makes it so that if the first reroll ends in a draw, there will keep being rerolls until there is no longer a draw.
            print("Player 1 rolls a", Roll1, "\n Player 2 rolls a",Roll2)
        if Roll1 > Roll2:
            print(Namae, "Wins!")
            #Prints a winning message.
        else:
            print(Namae2, "Wins!")
            #This prints a winning message
    elif P1total > P2total:
        print(Namae, "wins!")
        Winner = Namae
        WinScore = P1total
        #This prints a message if player 1 wins
    else:
        print(Namae2, "wins!")
        Winner = Namae2
        WinScore = P2total
        #This prints a message if player 1 wins.
        #Winscore and Winner are used to append the winner to a file later on.

    LeaderboardFile = open("Leaderboard.txt", "a+")
    #This opens the file to be appended
    FullFileInput = Winner + "," + str(WinScore) + "\n"
    #This combines the two variables from earlier into one, to make it easier to append.
    LeaderboardFile.write(FullFileInput)
    #This appends FullFileInput to the file.
    LeaderboardFile.close
    #Closes the File.

    print("Top 5 Scores:")
    LeaderboardFile = open("Leaderboard.txt", "r")
    #Opens the file for reading.
    Array = []
    #Creates an empty array
    FileLength = len(open("Leaderboard.txt").readlines())
    #This reads how many lines the file has
    for counter in range(FileLength):
        record = LeaderboardFile.readline()
        cells = record.split(",")
        #This splits the file every time there is a comma
        Array.append(cells)
        SortedArray = sorted(Array, key = lambda x: x[1])
        #This sorts the list in descending order, using score.

        x = 1
        for counter in range(0,5):
            print(len(SortedArray))
            holder = SortedArray[(len(SortedArray)-x)]
            #This causes an error, for seemingly no reason.
            print(x, ":",holder[0], holder[1])
            #This prints the leaderboard, one line at a time.
            x = x + 1
            #Increments x by 1.

elif MenuChoice == 3:
    print("Top 5 Scores:")
    LeaderboardFile = open("Leaderboard.txt", "r")
    Array = []
    FileLength = len(open("Leaderboard.txt").readlines())
    for counter in range(FileLength):
        record = LeaderboardFile.readline()
        cells = record.split(",")
        Array.append(cells)
        SortedArray = sorted(Array, key = lambda x: x[1])

        x = 1
        for counter in range(5):
            holder = SortedArray[(len(SortedArray)-x)]
            print(x, ":",holder[0], holder[1])
            x = x + 1
#Lines 198 to 211 are all copied and pasted from the leaderboard earlier.


#This code is a formatting disaster, I'm sorry.

在玩了一会儿游戏后,每次尝试显示排行榜时都会出现错误,我有一些文件。

排行榜.txt :

包含以下格式的评分:

Username1,score
Username2,score

等等...

Usernames.txt :包含所有有效的用户名。

我希望结果是这样的:

Top 5 Scores:

1: Alpha 100
2: Beta 91
3: Gamma 85
4: Delta 76
5: Epsilon 69

相反,代码打印:

Top 5 Scores:

1: Alpha 1

2: Alpha 1

(这总是将文件中的第一个值打印两次,而不对其进行排序。)

然后我收到错误:

Traceback (most recent call last):
  File "main.py", line 200 in <module>
    holder = SortedArray[(len(SortedArray)-x)]
IndexError: list index out of range.

'IndexError: list index out of range' 表示您的列表索引超出范围。 您正试图引用一些甚至不存在的索引。

holder = SortedArray[(len(SortedArray)-x)]
x = x + 1

例如,如果 x 大于 (len(SortedArray),您将得到一个可以触发该错误的负索引。

我希望你不介意,但我重写了你的一部分代码。

elif MenuChoice == 3:
    print("Top 5 Scores:")
    Array = []
    try:
        with open("Leaderboard.txt", "r") as LeaderboardFile:
            for l in LeaderboardFile.readlines():
                name, score = l.split(',')
                name = name.strip()
                score = int(score.strip())
                Array.append([name, score])
    except Exception:
        print('FileNotFound')

    Array = sorted(Array, key = lambda x: x[1], reverse=True)
    for i in range(5):
        print(f'{i+1}: {Array[i][0]} {Array[i][1]}')

请注意下一次,因为这个问题非常特定于您自己的代码,所以不太适合 SO,但更适合https://codereview.stackexchange.com/

祝你的家庭作业好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM