Python:类型错误:“str”对象不支持项目分配

2023-11-30

我在制作简单的战舰游戏时遇到这个问题。这是我的代码:

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”,但随后它说

类型错误:“str”对象不支持项目分配。


for i in range(5): #<<<<determine the board size here
    board.append(joined_O)

这对我来说看起来不太合适。您应该将列表附加到board,不是字符串。我猜你以前有过类似的经历:

for i in range(5):
    board.append(row)

这至少是正确的类型。但是这样你就会遇到奇怪的错误,每当你错过一艘船时,就会出现五个 X,而不是一个。这是因为每一行都是同一行;对一个人做出改变就会改变所有人。您可以通过每次使用切片技巧复制该行来避免这种情况。

for i in range(5): #<<<<determine the board size here
    board.append(row[:])

现在您的 X 应该正确分配。但print(board)在你的else块会有点难看。您可以使用几个快速连接很好地格式化它,而无需括号和引号:

else:
    print('Missile missed the target')
    board[int(missile_row)][int(missile_col)] = 'X'
    print("\n".join("  ".join(row) for row in board))

现在你已经得到了一些相当不错的输出。

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python:类型错误:“str”对象不支持项目分配 的相关文章

随机推荐