无法更新嵌套列表中的值

时间:2018-01-04 16:38:25

标签: python

我正在为一个班级项目写一个井字游戏。基本上我有这个清单:

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]

1 个答案:

答案 0 :(得分:2)

在循环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]