python - 无法更新嵌套列表中的值

标签 python

我正在为一个类(class)项目编写一个井字棋游戏。基本上我有这个列表:

grid = [[1,2,3],[4,5,6],[7,8,9]]

我只想根据玩家的不同用 X 或 O 更新列表值。我尝试使用以下函数来做到这一点,其中 p 是用户输入的整数(是的,我确保输入实际上是整数而不是字符串):

def place_sym(p):
    global turn
    global grid
    global plyr

    for r in grid:
        for c in r:
            if c == p:
                grid[r][c] = plyr[turn] # This is the line causing trouble.

当我运行此代码时,我收到一条错误消息,指出列表索引必须是整数而不是列表类型。或者,我尝试简单地用此行替换变量 c 而不是 grid[r][c] = plyr[turn]

c = plyr[turn]

打印c的值和类型发现c是int,并且与用户输入的值匹配。所以我可以找到变量,并且类型匹配,我只是无法更新原始列表中的值。我是否错误地使用了全局变量?我不明白为什么它不会更新。这是到目前为止的整个程序:

grid = [[1,2,3],[4,5,6],[7,8,9]]
plyr = ("X","O")
turn = 0

def drw_brd():
    i = 1
    f = turn
    for spc in grid:
        print " " + str(spc[0]) + " | " + str(spc[1]) + " | " + str(spc[2]) + " "
        if i<=2:
            print "-----------"
            i+=1

    print''
    print "Player %s (%s's) it's your turn!" %(str(f+1),plyr[turn])
    place = input('Cell number to take:')
    place_sym(int(place))
    check_win()

#def san_in(x):
#    if x not in range(1,9):
#        print "Please enter a number 1 through 9."

def check_win():
    switch_plyr()

def switch_plyr():
    global turn

    """
    if turn == 0:
        turn = 1
    else:
        turn = 0
    """
    if turn <= 0:
        turn = 1
    elif turn >= 1: 
        turn = 0

    #print turn
    drw_brd()

def place_sym(p):
    global turn
    global grid
    global plyr

    for r in grid:
        for c in r:
            if c == p:
                c = plyr[turn]

最佳答案

在循环中,rc 是行和列,而不是它们的索引。您需要跟踪索引才能更新值。您可以使用 enumerate function 来执行此操作.

def place_sym(p):
    global turn
    global grid
    global plyr

    # row_index will be 0, 1 or 2 (the position in grid).
    # row is an array of 3 integers.
    for row_index, row in enumerate(grid):
        # column_index will be 0, 1, 2 (the position in the row)
        # column_value is the actual integer value to check against
        for column_index, column_value in enumerate(row):
            if column_value == p:
                grid[row_index][column_index] = plyr[turn]

关于python - 无法更新嵌套列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48099712/

相关文章:

python - 递归函数不返回值

python - 如何从另一个模块扩展模板?

python - 使用索引和列名称作为 x 和 y 使用 pandas 数据框创建 Hexbin 图

python - Numpy reshape 2D 到 3D : moving columns to "depth"

Python 将日期转换为日期时间

python - 第一个python脚本,刮板,欢迎使用建议

python - 从 Pandas 写入 Excel 时设置默认数字格式

python - 类型错误 : 'range' object is not callable

python - 对 HLS jpeg 图像进行颜色阈值处理

python - scipy.optimize 最小化的结果关闭