Python:TypeError:'str'对象不支持项目分配 [英] Python: TypeError: 'str' object does not support item assignment
问题描述
我在制作一个简单的战舰游戏时遇到了这个问题.这是我的代码:
I have this problem while making a simple battleship game. Here is my code:
board = []
row = ['O'] * 5 #<<<<determine the board size here
joined_O = ' '.join(row)
for i in range(5): #<<<<determine the board size here
board.append(joined_O)
print(joined_O)
from random import randint #<<<< this code is to determine where the ship is. It is placed randomly.
ship_row = randint(1,len(board))
ship_col = randint(1,len(board))
print(ship_row,', ',ship_col,'\n')
print('Shoot missile to the ship')
missile_row = int(input('row : '))
missile_col = int(input('column: '))
#I really don't know where you're supposed to put the int() thingy so i put it everywhere
if int(missile_row) == int(ship_row) and int(missile_col) == int(ship_col):
print("Congratulation! You've hit the ship.")
break
elif int(missile_row) >= len(board) or int(missile_col) >= len(board):
print('Sorry! Area is out of range.')
break
else:
print('Missile missed the target')
board[int(missile_row)][int(missile_col)] = 'X'
print(board)
我试图重新分配导弹击中X"的O",但它说
I tried to reassign the 'O's where the missile hit with an 'X' but then it says
类型错误:'str' 对象不支持项目分配.
TypeError: 'str' object does not support item assignment.
推荐答案
for i in range(5): #<<<<determine the board size here
board.append(joined_O)
这在我看来不太合适.您应该将列表附加到 board
,而不是字符串.我猜你以前有过这样的经历:
This doesn't look right to me. You should be appending lists to board
, not strings. I'm guessing that you previously had something like:
for i in range(5):
board.append(row)
这至少是正确的类型.但是你会遇到奇怪的错误,每当你错过一艘船时,就会出现五个 X 而不是一个.这是因为每一行都是同一行;对一个进行更改会更改所有这些.您可以通过每次使用切片技巧制作该行的副本来避免这种情况.
Which would at least be the right type. But then you'd have weird bugs where five Xes appear instead of one whenever you miss a ship. This is because each row is the same row; making a change to one makes a change to all of them. You can avoid this by making a copy of the row each time using the slicing trick.
for i in range(5): #<<<<determine the board size here
board.append(row[:])
现在您的 X 应该正确分配.但是 else
块中的 print(board)
会有点难看.您可以使用几个快速连接在没有括号和引号的情况下很好地格式化它:
Now your Xes should assign properly. But print(board)
in your else
block will be a bit ugly. You can format it nicely without brackets and quote marks using a couple quick joins:
else:
print('Missile missed the target')
board[int(missile_row)][int(missile_col)] = 'X'
print("\n".join(" ".join(row) for row in board))
现在你得到了一些不错的输出.
Now you've got some pretty nice output.
Shoot missile to the ship
row : 1
column: 1
Missile missed the target
O O O O O
O X O O O
O O O O O
O O O O O
O O O O O
这篇关于Python:TypeError:'str'对象不支持项目分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!