Python:IndexError:列表索引超出范围

Posted

技术标签:

【中文标题】Python:IndexError:列表索引超出范围【英文标题】:Python: IndexError: list index out of range 【发布时间】:2012-03-04 14:07:54 【问题描述】:

我想我的程序已经完成了,但是……它不起作用。我正在尝试编写一个模拟彩票游戏的程序,但是当我尝试检查用户的猜测与彩票上的猜测次数时,我收到一个错误,告诉我“列表索引超出范围”。我认为这与我将随机数字分配给“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

【问题讨论】:

阅读回溯,在大多数情况下会有所帮助。 wining_numbers 多长时间?我想你会发现它a=randint(1,30) inside while 循环。否则,它只会运行一次。 另外,绝对没有理由在函数getguess中使用del myList[:]这一行,guess是在函数范围内定义的。用guess = []初始化猜测。 IndexError: list assignment index out of range 的可能重复项 【参考方案1】:

正如错误说明,问题出在以下行:

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 列表中的元素并不多。

【讨论】:

实际上,他的错误是在更早的时候引起的。根据他的输入语句,bubble 是一个字符串列表。然后,此列表将附加到 guess。所以guess 看起来像:[['12', '30', '12', '23'. '3'], ['4','5','7','8','16']]。正确的列表方法是guess.extend()。此外,这些值是字符串,因此即使它们进行比较,比较也将永远返回 true。【参考方案2】:

这是您的代码。我假设您正在使用 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()

【讨论】:

【参考方案3】:

我认为您的意思是将随机 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 不在winning_numbers 中时才会运行此代码。换句话说,如果有重复,则不会附加任何数字。请记住,while 会在运行前检查运行条件。

以上是关于Python:IndexError:列表索引超出范围的主要内容,如果未能解决你的问题,请参考以下文章

IndexError:列表索引超出范围(Python)

Python:IndexError:列表索引超出范围 Caeser Cipher

Python 3.6“IndexError:列表索引超出范围”

我继续得到indexerror:python上的索引列表超出范围

KeyError:“likeCount”和IndexError:Python中的列表索引超出范围

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