简体   繁体   English

如何使用用户输入更改列表元素?

[英]How do I change the element of a list with user input?

I'm trying to change an element of a list by doing this: 我试图通过这样做来改变列表的元素:

board = []
for i in range(3):
    board.append("-"*3)

def print_board(board):
    for row in board:
        print " ".join(row)

print_board(board)
print "Welcome to tic tac toe. You go first because I say so."
column = int(raw_input("Enter column number: "))
row = int(raw_input("Enter row number: "))

board[row][column] = "O" #THIS ONE
print_board(board)

but the error message "TypeError: 'str' object does not support item assignment" shows up. 但错误消息“TypeError:'str'对象不支持项目分配”显示。 What should I do? 我该怎么办?

'-' * 3 is a string and you want a list. '-' * 3是一个字符串,你想要一个列表。

So you should replace this : 所以你应该替换这个:

board.append("-"*3) # '---'

with this : 有了这个 :

board.append(['-']*3) # ['-','-','-']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM