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

13 投票
4 回答
316599 浏览
提问于 2025-04-17 12:56

我觉得我的程序已经完成了,但……它不工作。我正在尝试写一个模拟彩票游戏的程序,但是当我试图将用户的猜测与彩票上的数字进行比较时,出现了一个错误,提示“列表索引超出范围”。我觉得这可能和我把随机数字分配给“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

4 个回答

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个数字)。

4

这是你的代码。我猜你在用Python 3,因为你用了print()input()这些函数:

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()
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列表中根本没有那么多元素。

撰写回答