列表索引必须是整数,而不是str.BATTLESHIP

2024-09-28 17:07:20 发布

您现在位置:Python中文网/ 问答频道 /正文

以下Python代码:

def CheckIfSunk(Board):
  Row, Column = GetRowColumn()

  if Board[Row][Column] == "A":
    Ships = "Aircraft Carrier"
  elif Board[Row][Column] == "B":
    Ships = "Battleship"
  elif Board[Row][Column] == "S":
    Ships = "Submarine" 
  elif Board[Row][Column] == "D":
    Ships = "Destroyer"
  elif Board[Row][Column] == "P": 
    Ships = "Patrol Boat"
  elif Board[Row][Column] == "P": 
    Ships = "Patrol Boat"
  elif Board[Row][Column] == "N": 
    Ships = "NEW"


  Board[-1][Ships] -= 1
  if Board[-1][Ships] == 0:
    print Ships + " Sunk" 

我收到这个错误:

Board[-1][Ships] -= 1 TypeError: string indices must be integers, not str

我怎样才能解决这个问题,任何帮助都将不胜感激


Tags: 代码boardifdefcolumnrowelifcarrier
2条回答

在代码的最后三行

船[-1][船]-=1

To refer the elements in 2-dimensional array i.e in PYTHON a list containing 2 lists we use integer values as index.

变量Ships是字符串None如果上述任何条件未满足,则Ships不是整数。你知道吗

TypeError: string indices must be integers, not str

因此,您需要使用整数访问列表(数组

Ships是一个字符串。 您的Board包含字符串,因此您试图通过str而不是通过index获取字符串的元素。你知道吗

翻译说的一模一样:

TypeError: string indices must be integers, not str

相关问题 更多 >