【问题标题】:'list index out of range' error with list - dictionary values列表中的“列表索引超出范围”错误 - 字典值
【发布时间】:2018-05-05 23:16:53
【问题描述】:

我创建了这个程序来“种植”西红柿并为它们分配成熟日期(以轮数为单位)。但是,当我尝试使用该日期时,系统会返回错误“列表索引超出范围”。我一生都无法理解为什么会这样。请理解我是一个初学者程序员,所以虽然我确实在寻找这个问题的答案,但我发现的大部分内容对我来说都是胡言乱语。谢谢!

#!/usr/bin/python
# -*- coding: utf-8 -*-
# this code is meant for testing a portion of farmboi simulator.
# this code is not the entire program.

tomato_seeds = 2
tomato_planted = 0
tomato = 0
tomato_id = 0
growing = {}  # keeps track of what items are currently growing
grown = []
turn = 0  # keeps track of what turn the player is on


# actually 'plants' the tomatoes

def plant(crop, amount):  # the error only runs when amount > 1
    global tomato_seeds
    global tomato_planted
    global tomato_id
    global growing
    global grown
    if crop == 'tomato':
        for i in range(amount):
            if tomato_seeds > 0:
                tomato_seeds -= 1
                tomato_planted += 1
                growing['tomato_' + str(tomato_id)] = turn + 5  
                # this creates a library that contains tomatoes and their turn of harvest
                grown.append('tomato_' + str(tomato_id))  
                # this list is so I can run a for loop using numbers (there's probably a better way to do this idk)
                tomato_id += 1
    else:
        print('You do not have any tomato seeds remaining\n')
        print(str(grown))
        print(str(growing))


# checks every loop to see if the tomatoes are ripe

def check_harvest():
    global tomato
    global tomato_planted
    harvested = 0
    for item in range(len(growing)):
        print('checker: ' + str(growing[grown[item]]))
        if growing[grown[item]] == turn:  
        # Im calling the value here the checker (this is also where the error occurrs)
            tomato += 1
            tomato_planted -= 1
            del growing[grown[item]]
            del grown[item]
        if harvested > 0:
            print('You have harvested ' + str(harvested) + ' tomatoes')


while True:
    if input('What would you like to do?\n').lower() == 'plant':
        plant('tomato', 2)

    check_harvest()
    turn += 1
    print('turn: ' + str(turn))

(可能某处存在缩进错误,忽略这一点。我无法将其作为代码放入堆栈溢出文本框)

【问题讨论】:

  • 能把错误写在这里吗?
  • Traceback(最近一次调用最后):文件“C:/Users/cavem/Documents/Python/Personal Python Files/Farmboi Simulator/Farmboi test.py”,第 52 行,在 check_harvest () 文件“C:/Users/cavem/Documents/Python/Personal Python Files/Farmboi Simulator/Farmboi test.py”,第 38 行,在 check_harvest print("checker:" + str(growth[grown[item]]) ) IndexError: 列表索引超出范围
  • @JakeShropshire 我能够毫无问题地运行您的代码。对 2 个函数进行了充电,并且 while 循环正确运行。当我第六次运行工厂时出现超出范围(见附图i.stack.imgur.com/VpQkp.png)

标签: python python-3.x list dictionary


【解决方案1】:

在函数check_harvest() 中,growing 字典的长度可能与grown 列表的长度不同。

plant() 会将amount 项添加到growing,但是,只会将一项添加到grown。所以,如果amount 大于一,字典和列表的长度就会不同。

然后check_harvest() 迭代growing 的长度,这可能比grown 长,这导致尝试访问grown 中的项目超出列表的限制。

如果你缩进这两行可能会解决问题:

            grown.append("tomato_" + str(tomato_id)) #this list is so I can run a for loop using numbers (there's probably a better way to do this idk)
            tomato_id += 1

这样它们就在 for 循环中:

            for i in range(amount):
                if tomato_seeds > 0:
                    tomato_seeds -= 1
                    tomato_planted += 1
                    growing["tomato_" + str(tomato_id)] = turn + 5 #this creates a library that contains tomatoes and their turn of harvest
                    grown.append("tomato_" + str(tomato_id)) #this list is so I can run a for loop using numbers (there's probably a better way to do this idk)
                    tomato_id += 1

但我不能确定,因为我不太了解您的代码。

【讨论】:

  • 缩进错误是我复制到堆栈溢出的问题。我想我不明白你的意思是字典和列表没有以相同的速度增长/耗尽。我认为 .append() 方法的作用与在字典中声明一个新项目相同(我很可能是错的)。我有点担心使用 del 函数,那么问题可能存在吗?
  • @JakeShropshire:那么您应该修复问题中的缩进。该错误可以通过您发布的代码来解释,但如果这不是您正在运行的代码,那么进行进一步猜测是徒劳的。此外,应将异常添加到问题中并正确格式化(作为代码)。
猜你喜欢
  • 2022-08-17
  • 2017-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多