Ошибка 'list index out of range' со списком - значения словаря - PullRequest
0 голосов
/ 05 мая 2018

Я создал эту программу, которая «сажает» помидоры и назначает им дату созревания (в единицах оборотов). Однако, когда я пытаюсь использовать эту дату, система возвращает ошибку «индекс списка вне диапазона». Я не могу на всю жизнь понять, почему это происходит. Пожалуйста, поймите, что я начинающий программист, поэтому, хотя я действительно искал ответ на эту проблему, многое из того, что я обнаружил, было для меня полным бредом. Спасибо!

#!/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))

(Возможно, где-то произошла ошибка отступа, не обращайте на это внимания. У меня возникли проблемы с переносом текста в текстовое поле переполнения стека в виде кода)

1 Ответ

0 голосов
/ 05 мая 2018

В функции 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

но я не уверен, так как я не совсем понимаю ваш код.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...