Python:索引错误:列表索引超出范围

13

我认为我已经完成了我的程序,但是...它不能运行。我正在尝试编写一个模拟彩票游戏的程序,但是当我试图检查用户的猜测是否与票据上的猜测相符时,我收到了一个错误,告诉我“列表索引超出范围”。我认为这与代码中分配随机数字给“a”、“b”、“c”等部分有关,但我不确定。

以下是完整的代码:

import random

def main():
random.seed()

#Prompts the user to enter the number of tickets they wish to play.
tickets = int(input("How many lottery tickets do you want?\n"))

#Creates the dictionaries "winning_numbers" and "guess." Also creates the variable "winnings" for total amount of money won.
winning_numbers = []
guess = []
winnings = 0

#Generates the winning lotto numbers.
for i in range(tickets):
    del winning_numbers[:]

    a = random.randint(1,30)
    while not (a in winning_numbers):
        winning_numbers.append(a)

    b = random.randint(1,30)
    while not (b in winning_numbers):
        winning_numbers.append(b)

    c = random.randint(1,30)
    while not (c in winning_numbers):
        winning_numbers.append(c)

    d = random.randint(1,30)
    while not (d in winning_numbers):
        winning_numbers.append(d)

    e = random.randint(1,30)
    while not (e in winning_numbers):
        winning_numbers.append(e)

    print(winning_numbers)
    getguess(guess, tickets)
    nummatches = checkmatch(winning_numbers, guess)

    print("Ticket #"+str(i+1)+": The winning combination was",winning_numbers,".You matched",nummatches,"number(s).\n")

    if nummatches == 0 or nummatches == 1:
        winnings = winnings + 0
    elif nummatches == 2:
        winnings = winnings + 10
    elif nummatches == 3:
        winnings = winnings + 500
    elif nummatches == 4:
        winnings = winnings + 20000
    elif nummatches == 5:
        winnings = winnings + 1000000

print("You won a total of",winnings,"with",tickets,"tickets.\n")

#Gets the guess from the user.
def getguess(guess, tickets):
del guess[:]

for i in range(tickets):
    bubble = input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split(" ")
    guess.append(bubble)
print(bubble)

#Checks the user's guesses with the winning numbers.
def checkmatch(winning_numbers, guess):
match = 0
for i in range(5):

    if guess[i] == winning_numbers[i]:
        match = match+1

return match

main()

以下是我收到的错误:

Traceback (most recent call last):
  File "C:\Users\Ryan\Downloads\Program # 2\Program # 2\lottery.py", line 85, in <module>
    main()
  File "C:\Users\Ryan\Downloads\Program # 2\Program # 2\lottery.py", line 45, in main
   nummatches = checkmatch(winning_numbers, guess)
File "C:\Users\Ryan\Downloads\Program # 2\Program # 2\lottery.py", line 79, in checkmatch
    if guess[i] == winning_numbers[i]:
IndexError: list index out of range

阅读回溯信息,在大多数情况下会很有帮助。 - monkut
获胜号码有多长?我认为你会发现它是<=5的。你的获胜号码生成器有缺陷。你需要将a=randint(1,30)放在while循环内部。否则,它只运行一次。 - Joel Cornett
1
另外,在使用del myList[:]这行代码时完全没有必要。在函数getguess中,guess是在函数作用域内定义的。请使用guess = []来初始化guess - Joel Cornett
可能是重复的问题:IndexError: list assignment index out of range - Lennart Regebro
4个回答

16

根据错误提示,问题出现在这一行:

if guess[i] == winning_numbers[i]

错误在于你的列表索引超出了范围——也就是说,你试图引用一些根本不存在的索引。在完全调试你的代码之前,我会检查你基于输入添加猜测的那行代码:

for i in range(tickets):
    bubble = input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split(" ")
    guess.append(bubble)
print(bubble)

你向用户提供的猜测次数的大小基于

# Prompts the user to enter the number of tickets they wish to play.
tickets = int(input("How many lottery tickets do you want?\n"))

所以如果他们想要的票数少于5张,那么你在这里的代码

for i in range(5):

if guess[i] == winning_numbers[i]:
    match = match+1

return match

会抛出一个错误,因为guess列表中没有那么多的元素。


4
实际上,他的错误是在稍早的地方导致的。根据他的输入语句,“bubble”是一个字符串列表。然后将此列表附加到“guess”上。因此,“guess”的样子应该是:[['12','30','12','23','3'],['4','5','7','8','16']]。正确的列表方法是 guess.extend()。此外,这些值是字符串,即使它们进行比较,比较也永远不会返回 true。 - Joel Cornett

4

这是你的代码。根据你使用的print()input()函数,我假设你使用的是Python 3版本:

import random

def main():
    #random.seed() --> don't need random.seed()

    #Prompts the user to enter the number of tickets they wish to play.

    #python 3 version:
    tickets = int(input("How many lottery tickets do you want?\n"))

    #Creates the dictionaries "winning_numbers" and "guess." Also creates the variable "winnings" for total amount of money won.
    winning_numbers = []
    winnings = 0

    #Generates the winning lotto numbers.
    for i in range(tickets * 5):
        #del winning_numbers[:] what is this line for?
        randNum = random.randint(1,30)
        while randNum in winning_numbers:    
            randNum = random.randint(1,30)
        winning_numbers.append(randNum)

    print(winning_numbers)
    guess = getguess(tickets)
    nummatches = checkmatch(winning_numbers, guess)

    print("Ticket #"+str(i+1)+": The winning combination was",winning_numbers,".You matched",nummatches,"number(s).\n")

    winningRanks = [0, 0, 10, 500, 20000, 1000000]

    winnings = sum(winningRanks[:nummatches + 1])

    print("You won a total of",winnings,"with",tickets,"tickets.\n")


#Gets the guess from the user.
def getguess(tickets):
    guess = []
    for i in range(tickets):
        bubble = [int(i) for i in input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split()]
        guess.extend(bubble)
        print(bubble)
    return guess

#Checks the user's guesses with the winning numbers.
def checkmatch(winning_numbers, guess):
    match = 0
    for i in range(5):
        if guess[i] == winning_numbers[i]:
            match += 1
    return match

main()

2

我认为你是想在循环内部生成随机的a,b,c等值:

a = None # initialise
while not (a in winning_numbers):
    # keep rolling an a until you get one not in winning_numbers
    a = random.randint(1,30)
    winning_numbers.append(a)

否则,a 只会生成一次,如果它已经在 winning_numbers 中,则不会被添加。由于 a 的生成是在 while 之外(在您的代码中),如果 a 已经在 winning_numbers 中,则很遗憾,它将不会重新生成,您将有一个较少的中奖号码。
这可能导致您在 if guess[i] == winning_numbers[i] 中出现错误。(您的 winning_numbers 并不总是长度为5)。

这段代码只有在a不在中奖号码列表中时才会运行。换句话说,如果有重复的数字,就不会添加任何数字。请记住,在运行之前,while会检查运行条件。 - Joel Cornett

0
您正在从一个空列表中寻找元素或者是寻找不存在的元素索引。例如:
>>> list1 = []
>>> list1[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> len(list1)
0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接