Python中的IndexError,我不明白为什么

时间:2018-11-02 22:54:03

标签: python

Python 3.7 Windows 7

我正在创建“ Connect 4”程序,但是在编辑列表值时遇到问题。

我的代码: 不要关注doctest,因为我还没有更新它们来显示更改

def get_piece(board, row, column):
    """Returns the piece at location (row, column) in the board.

    >>> rows, columns = 2, 2
    >>> board = create_board(rows, columns)
    >>> board = put_piece(board, rows, 0, 'X')[1] # Puts piece "X" in column 0 of board and updates board
    >>> board = put_piece(board, rows, 0, 'O')[1] # Puts piece "O" in column 0 of board and updates board
    >>> get_piece(board, 1, 0)
    'X'
    >>> get_piece(board, 1, 1)
    '-'
    """
    breakloop = False
    if row < 0:
        breakloop = True
        return breakloop
    return row, board[row][column]

def create_board(rows, columns):
    """Returns a board with the given dimensions.

    >>> create_board(3, 5)
    [['-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-']]
    """
    return [create_row(columns) for i in range(rows)]

def make_move(board, col, player):
    """Put player's piece in column COL of the board, if it is a valid move.

    """
    assert col <= len(board[1]) and not col < 0, "Move must be bewteen 0 and " + len(board[1])

    row, piece = get_piece(board, len(board[1]), col)
    while piece == "X" or piece == "Y":
        row, piece = get_piece(board, len(board[1])-1, col)
        if breakloop:
            assert "That column is full"
    return replace_elem(board, row, col, player)

def replace_elem(board, row, col, elem):
    """Create and return a new list whose elements are the same as those in
    LST except at index INDEX, which should contain element ELEM instead.

    >>> old = [1, 2, 3, 4, 5, 6, 7]
    >>> new = replace_elem(old, 2, 8)
    >>> new
    [1, 2, 8, 4, 5, 6, 7]
    >>> new is old   # check that replace_elem outputs a new list
    False
    """

    board[row][column] = elem
    return board

def create_row(size):
    """Returns a single, empty row with the given size. Each empty spot is
    represented by the string '-'.

    >>> create_row(5)
    ['-', '-', '-', '-', '-']
    """
    return  ['-' for i in range(size)]

当我使用len(board [0])或len(board [1])时,它给了我一个预期的数字。当我使用len调用get_board时,它会给我:

 Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    make_move(z, 2, "X")
  File "C:\Users\comp\Documents\cs61a\Practice.py", line 54, in make_move
    row, piece = get_piece(board, len(board[1]), col)
  File "C:\Users\comp\Documents\cs61a\Practice.py", line 17, in get_piece
    return row, board[row][column]
IndexError: list index out of range

但是当我直接使用数字时,效果很好。

1 个答案:

答案 0 :(得分:0)

简单地说,就像Python所说的那样,您的make_move()函数调用get_piece()的行或列的值超出了索引的允许范围。 特别是函数的第七行,您在此处调用第一时间get_piece()。您在-1附近忘记了len(board[1]),因此您传递的是列表的长度5,因此当您尝试读取列表时,Python会引发错误。

row, piece = get_piece(board, len(board[1]), col) #errata
row, piece = get_piece(board, len(board[1]) - 1, col) #correct