【问题标题】:IndexError: list index out of range? PythonIndexError:列表索引超出范围? Python
【发布时间】:2017-04-27 00:15:29
【问题描述】:

所以我创建了一个游戏,将宝箱和土匪放在一个网格中,并允许玩家在其中移动。本质上,如果玩家降落在随机放置在网格内的宝箱上,他们的硬币总数会增加 10,如果玩家降落在土匪身上,则硬币总数会重置为 0。

但是,如果某个特定的宝箱被访问过 3 次,我试图让该程序将其变成强盗。我已经使用列表 visit[]visited[] 这样做,但是我一直收到错误:

IndexError: list index out of range

我不知道为什么?我已附上所有代码以供参考,并概述了似乎导致问题的部分。如何摆脱错误,使胸部在第三次访问后变成土匪?(第四次)

Traceback: 
line 130, in <module>
    visits[i] += 1
IndexError: list index out of range

choice = 0
b = 0
player_location = ' X '
x = 8
y = 0
coins = 0
bandits = 5
treas_chests = 10
a = 1
import random
x_move = 0
y_move = 0
no_of_bands = 5
size_of_grid = 8
chests = []
bandits = []
size_of_grid_n = 0
visits = []
visited = []
def menu(): 
    print('If you would like to play the Treasure Hunt , press 1') 
    choice = input('If not, press any key to exit \n') 
    if choice == '1': 
        print('Great! You have made the right choice :)') 
    else: 
        print('Goodbye.') 
        quit() 
menu() 
def board(): 
    new_board = [ ]
    top_row = [' 1 ',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 ',' 8 ']

    new_board.append(top_row)

    for x in range(0, 8):
        row = [' 0 '] * size_of_grid
        new_board.append(row)

    return new_board

def print_board(b):
  row_numbers = [' ', '1', '2', '3', '4', '5', '6', '7', '8']
  i = 0
  for row in b:
    print (row_numbers[i], ''.join(row))
    i = i + 1
current_x_loc = 0
current_y_loc = size_of_grid

def update_board(b, current_y_loc, current_x_loc):
    #b[current_y_loc-y_move][current_x_loc+x_move] = player_location
    while (-1 >= current_y_loc-y_move) or (current_y_loc -y_move > size_of_grid):
        print('INVALID INPUT')
        get_move()
    while (-1 >= current_x_loc + x_move) or (current_x_loc + x_move > size_of_grid):
        print('INVALID INPUT')
        get_move()
    b[current_y_loc - y_move][current_x_loc + x_move] = player_location
    current_y_loc -= y_move
    current_x_loc += x_move
    print("current location = ", current_x_loc, current_y_loc)
    return current_y_loc, current_x_loc

def chests_and_bandits():
    num = 0
    while num < treas_chests:
        y_c = random.randint(1, size_of_grid)  
        x_c = random.randint(1, size_of_grid)
        location = [y_c, x_c]
        while (location in location) or (location == [size_of_grid, 0]):
            y_c = random.randint(1, size_of_grid)
            x_c = random.randint(1, size_of_grid)
            location=[y_c, x_c]
        chests.append(location)
        num = num + 1

    num = 0
    print(chests)
    while num < no_of_bands:
        y_b = random.randint(1, size_of_grid)
        x_b = random.randint(1, size_of_grid)
        location=[y_b, x_b]
        while (location in location) or (location in chests) or (location == [size_of_grid, 0]):
            y_b = random.randint(1, size_of_grid)
            x_b i= random.randint(1, size_of_grid)
            location = [y_b, x_b]
        bandits.append(location)
        num = num + 1
    print(bandits)

while a == 1:
    chests_and_bandits()
    def get_move():
        advice = 'Please enter your move in two integers, vertical, then horizontal, separated by a space.  Use positive numbers for up and right, negative for down and left.'
        example = 'For example, an input of \'2 2\' would be 2 moves vertically, and 2 moves horizontally.'
        move = input(advice + example)
        coor=move.split()
        while len(coor) != 2:
            print('Invalid input- too many or too few co-ordinates')
            print('')
            advice = 'Please enter your move in two integers, vertical, then horizontal, separated by a space.  Use positive numbers for up and right, negative for down and left.'
            example = 'For example, an input of \'2 2\' would be 2 moves vertically, and 2 moves horizontally.'
            move = input(advice + example)
            coor = move.split()
        move = move.split()
        y_move, x_move = move
        x_move = int(x_move)
        y_move = int(y_move)
        return x_move, y_move

    while True:
        new_board = board()
        current_y_loc, current_x_loc = update_board(new_board, current_y_loc, current_x_loc)
        print_board(new_board)
        print(' ')
        print(current_x_loc, current_y_loc)
        cur_loc = [current_x_loc, current_y_loc]

下面的部分是使用出现错误的列表的地方

        for i in range (0, len(chests)):
            if cur_loc == chests[i]:
                coins += 10
                print('You have found a treasure chest')
                print('Number of coins: ',coins)
                print('')
                visits[i] += 1
                if visits[i] > 3:
                    visited[i] = True
                    bandits.append(chests[i])
                    var = chests[i]
            for i in range(0, len(visited)):
                chests.remove
                if visits[i] == 3:
                    treas_chests -= 1
                    no_of_bands += 1
                    bandits.append(chests[i])
                    var = chests[i]
        for i in range (0, len(bandits)):
            if cur_loc == bandits[i]:
                coins = 0
                print('You have hit a bandit')
                print('Number of coins: ', coins)
                print('')


        x_move, y_move = get_move()

【问题讨论】:

  • 当我运行你的代码时,我得到一个无限循环,资源管理器卡在 0,8
  • 好像chestsvisits
  • @Prune 我认为那是因为您只运行了代码的第一部分,而在 blockquote 之后省略了代码
  • 知道了。关闭投票被撤回。

标签: python list runtime-error


【解决方案1】:

您对range (0, len(chests)) 进行迭代,然后在visits[i] += 1 行中出现错误。看起来 chestsvisits 的长度不相等。我在visits 列表中看不到任何appends,所以它基本上是空的。

此外,您正在嵌套循环中混合计数器:

for i in range (0, len(chests)):
    ...
    # you override the i value here
    for i in range(0, len(visited)):

只做内部循环其他其他计数器,例如j:

for i in range (0, len(chests)):
    ...
    for j in range(0, len(visited)):

另外你使用的是len(visited),但是超过visits[i],但是不能保证这两个数组长度相等。

【讨论】:

  • 我不认为这是问题所在 - 看起来访问列表没有值,并且当它不存在时,他试图增加访问 [i] 的值。他混淆了计数器并需要修复它,因为这会导致不同的错误
  • @VMAtm 我只是有点困惑,为什么数组必须等长?
  • 您正在通过索引从另一个数组访问一个数组,因此它们必须相等。现在其中一个是空的
  • @VMAtm 好的,我明白了。谢谢