【问题标题】:list indices must be integers, not str. BATTLESHIP列表索引必须是整数,而不是 str。战舰
【发布时间】:2016-07-20 05:03:53
【问题描述】:

以下 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: 字符串索引必须是整数,而不是 str

我该如何解决这个问题,非常感谢任何帮助

【问题讨论】:

    标签: python string python-2.7 integer indices


    【解决方案1】:

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

    译者说的一模一样:

    TypeError: string indices must be integers, not str
    

    【讨论】:

    • 感谢您的快速回复,我不是最擅长python,所以我还是有点困惑
    • 位置-1的Board是一个字符串,而不是一个字典。所以你不能用另一个字符串访问这个字符串。你应该有像 Board[-1] = {'Battleship': 10, ...} 这样的东西。相反,您有类似 Board[-1] = 'oh my'
    【解决方案2】:

    在代码的最后第三行

    Board[-1][Ships] -= 1

    要引用二维数组中的元素,即在 PYTHON 中包含 2 个列表的列表,我们使用 整数 值作为索引。

    Ships 变量是 String None 如果不满足上述任何条件,则无论哪种方式 Ships 都不是整数。

    TypeError:字符串索引必须是整数,而不是 str

    因此,您需要使用 整数

    访问列表(数组

    【讨论】:

      猜你喜欢
      • 2017-01-27
      • 2016-02-09
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      相关资源
      最近更新 更多