python - 如何在 Python 中填充二维数组?

标签 python arrays python-3.x 2d

这是我的代码:

empty = ' '
board = [[empty, empty, empty], [empty, empty, empty], [empty, empty, empty]]

def print_board():
    for idx, val in enumerate(board):
        print(val)

def board_update(x,y,player):
    board[x:y] = player;

game_is_running = True
player = 'x'
print_board()



while game_is_running:
    if player == 'x':
        print ('x turn')
        ver = int(input('input vertical of x '))
        hor = int(input('input horizontal of x '))
        board_update(ver, hor, player)
        player = 'o'
    print_board()

    if player == 'o':
        print ('o')
        vertical = int(input('input vertical of o '))
        horizontal = int(input('input horizontal of o '))

每当我运行代码时,它都会像这样放置字母:

[' ', ' ', ' ']

x

[' ', ' ', ' ']

[' ', ' ', ' ']

如何让它看起来像这样:

[' ', ' ', ' ']

[' ', x ,  ' ']

[' ', ' ', ' ']

最佳答案

这里的问题是一致的

board[x:y] = player;

[x:y] 表示法用于分配范围,而您真正需要的可能是

board[x][y] = player

通常您会收到错误,因为将单个值分配给范围会抛出TypeError。在这种情况下,您正在分配 python 将其视为字符列表的字符串。

关于python - 如何在 Python 中填充二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42873672/

相关文章:

python 3.0 "with"语法错误?

python - 1.2.x 中的 Django ManyToMany 内联排序

python - 安装 pygrip 和 conda forge

javascript - 如何在 ReactJs 中打印出用户输入的数组

python - Numpy argwhere 不等式条件

python - 如何使用 openpyxl 确定 Excel 工作表是否不包含任何值?

python - Pandas 数据框 : perform calculations on columns

python - 将 numpy 数组堆叠到对角线上

php - 如何在不传递数组的情况下使类可以访问数组?

django - mod_wsgi 错误 : ModuleNotFoundError: No module named 'django'