Python 更改二维列表中的项目时出错

Python error in changing item in 2d list

我正在制作井字游戏,无法将 player/computer 的符号分配给二维列表。

 array = []
 player_choice = 0
 computer_choice = 0
 player_move_col = 0
 player_move_row = 0


def starting_array(start_arr):
    for arrays in range(0, 3):
        start_arr.append('-' * 3)


def print_array(printed_arr):
    print printed_arr[0][0], printed_arr[0][1], printed_arr[0][2]
    print printed_arr[1][0], printed_arr[1][1], printed_arr[1][2]
    print printed_arr[2][0], printed_arr[2][1], printed_arr[2][2]


def player_sign():
    choice = raw_input("Do you want to be X or O?:  ").lower()
    while choice != 'x' and choice != 'o':
        print "Error!\nWrong input!"
        choice = raw_input("Do you want to be X or O?:  ").lower()
    if choice == 'x':
        print "X is yours!"
        return 2
    elif choice == 'o':
        print "You've chosen O!"
        return 1
    else:
        print "Error!\n Wrong input!"
        return None, None

def player_move(pl_array, choice, x, y):    # needs played array, player's sign and our col and row
    while True:
        try:
            x = int(raw_input("Which place do you choose?:  ")) - 1
            y = int(raw_input("What is the row? ")) - 1
        except ValueError or 0 > x > 2 or 0 > y > 2:
            print("Sorry, I didn't understand that.")
            # The loop in that case starts over
            continue
        else:
            break
    if choice == 2:
        pl_array[x][y] = 'X'
    elif choice == 1:
        pl_array[x][y] = "O"
    else:
        print "Choice didn't work"
    return pl_array, x, y

starting_array(array)
print_array(array)
# print player_choice, computer_choice - debugging
player_move(array, player_sign(), player_move_col, player_move_row)
print_array(array)

它给我一个错误:

pl_array[x][y] = "O"
TypeError: 'str' object does not support item assignment

我如何更改代码以使其更改我向程序显示的项目以在其中写入 "X" 或 "O"?

就像错误所说的那样,'str'对象不支持项目分配,也就是说你不能这样做:

ga = "---"
ga[0] = "X"

但是您可以通过更改以下内容在您的示例中使用列表:

start_arr.append('-' * 3)

start_arr.append(["-"] * 3)