【问题标题】:"List indices must be integers or slices, not tuple" error“列表索引必须是整数或切片,而不是元组”错误
【发布时间】:2017-11-04 00:19:35
【问题描述】:

我是编码初学者,目前正在制作 rpg。当我运行代码时,它给了我上述错误。给我错误的部分是print("You are on " + floors[currentRoom] + ". You find " + floorsFeature[currentRoom])。我的猜测是 floors、floorsFeature 和 currentRooms 一定有问题。因为我是初学者,所以我不确定错误是什么意思。有人可以简单解释一下吗?

print("You are finally a Pokemon trainer! Today, you have gotten your very first Pokemon, a Bulbasaur!")
name = input("What will you name your Bulbasaur? ")
print("Unfortunately, " + name + " doesn't seem to obey or like you...")
print("You try to be friendly to " + name + ", but it just won't listen...")
print("As " + name + " was busy ignoring you, something seems to catch its attention and it runs off!")
print("You chase after " + name + ", but it's too fast! You see it running into an abandoned Pokeball Factory.")
print("You must explore the abandoned Pokeball Factory and find " + name + " before something happens to it!")
print()
print("You may input 'help' to display the commands.")
print()

gamePlay = True
floors = [['floor 1 room 1', 'floor 1 room 2', 'floor 1 room 3', 'floor 1 room 4'],['floor 2 room 1', 'floor 2 room 2', 'floor 2 room 3', 'floor 2 room 4', 'floor 2 room 5'],['floor 3 room 1,' 'floor 3 room 2', 'floor 3 room 3'],['floor 4 room 1', 'floor 4 room 2']]
floorsFeature = [['nothing here.', 'nothing here.', 'stairs going up.', 'a Squirtle.'],['stairs going up and a pokeball.', 'a Charmander.', 'a FIRE!!!', 'stairs going down.', 'a pokeball.'],['stairs going down.', 'a door covered in vines.', '2 pokeballs!'],['your Bulbasaur!!!', 'an Eevee with a key tied around its neck.']]
currentRoom = [0][1]
pokemonGot = []
count = 0
bagItems = []
countItems = 0

while gamePlay == True:
    print("You are on " + floors[currentRoom] + ". You find " + floorsFeature[currentRoom])
    move = input("What would you like to do? ")
    while foo(move) == False:
        move = input("There's a time and place for everything, but not now! What would you like to do? ")
    if move.lower() == 'left':
        if currentRoom > 0:
            currentRoom = currentRoom - 1
            print("Moved to " + floors[currentRoom] + ".")
        else:
            print("*Bumping noise* Looks like you can't go that way...")
    elif move.lower() == 'right':
        if currentRoom < len(floors) - 1:
            currentRoom = currentRoom + 1
            print("Moved to " + floors[currentRoom] + ".")
        else:
            print("*Bumping noise* Looks like you can't go that way...")
    elif move.lower() == 'help':
        print("Input 'right' to move right. Input 'left' to move left. Input 'pokemon' to see what Pokemon are on your team. Input 'bag' to see the items you are carrying. Input 'help' to see the commands again.")
    elif move.lower() == 'pokemon':
        if count == 0:
            print("There are no Pokemon on your team.")
        else:
            print("The Pokemon on your team are: " + ", ".join(pokemonGot) + ".")
    elif move.lower() == 'bag':
        if countItems == 0:
            print("There are no items in your bag.")
        else:
            print("The items in your bag are: " + ", ".join(bagItems) + ".")
    print()

【问题讨论】:

  • currentRoom = [0][1] 这段代码正确吗?只是为了仔细检查
  • 'floor 3 room 1,' 'floor 3 room 2', ... 出现另一个拼写错误,逗号应该不在引号内。

标签: python python-3.x


【解决方案1】:

让我们分部分来:

提供所有需要的代码:

我们不知道foo() 函数的作用。它似乎是一个验证功能,但我们缺少那部分代码。请始终提供一段代码,我们可以运行它来检查您的错误。

foo()替换:

要根据一组有效的选项检查选择,您可以在一行中完成:

1 in [1, 2, 3] # Output: True
4 in {1, 2, 3} # Output: False
4 not in {1, 2, 3} # Output: True
"b" in ("a", "b", "c") # Output: True
"abc" in ("a", "b", "c") # Output: False
"a" in "abc" # Output: True

如您所见,我使用了不同的值(intstr)和不同的容器(listsettuplestr,...),我可以使用更。使用not in 会给你与预期相反的答案。在您的情况下,您可以使用:

commands = {'help', 'pokemons', 'bag', 'left', 'right'}
while move not in commands:
    ...

字符串格式:

有多种方法可以格式化字符串以在其中包含变量值,但最 Python 的方法是使用 str.format()。您可以查看有关格式化字符串如何工作的文档here,但最简单的示例是:

print("Unfortunately, {} doesn't seem to obey or like you...".format(name))

基本上,您使用由{} 分隔的占位符,然后使用您要放置的参数调用.format() 函数。在{} 中,您可以放置​​不同的附加字符串来格式化输出,例如确定浮点数的小数位数。

lists 和 tuples:

Python 中的lists 和tuples 都是序列容器。主要区别在于 list 是可变的,而 tuple 不是。它们都使用从0 开始的var[position] 表示法访问。因此,如果您不打算更改序列的内容,则应该使用tuple 而不是列表来强制解释器执行它并提高内存效率。您对元组使用括号而不是方括号。

dicts

dicts 是保持状态的好方法:

player = {
          'floor': 1,
          'room': 2,
          'pokemons': [],
          'bag': [],
         }

您不必存储数组的长度:

在某些语言中,您总是将项目的数量保存在存储的数组中。 Python 的容器可以在运行时通过调用len(container) 来确定它们的大小。您在代码的某些部分使用了它,但您保留了一个不需要的 countcountItems 变量。

多维列表(又称矩阵):

您似乎在处理矩阵时遇到了一些问题,请使用以下符号:matrix[i][j] 访问i+1th 列表的j+1th 元素(从0 开始)。

matrix = [
          [1, 2, 3],
          [4, 5, 6],
          [7, 8, 9],
         ]
print(matrix[1][2]) # Output: 6

要了解列表的数量,在您的案例楼层中,请使用len(matrix)。要知道第 n 个列表的元素数量,请使用 len(matrix[n-1])

最终代码:

commands = {'help', 'pokemons', 'bag', 'left', 'right', 'exit'}

gamePlay = True
features = (
            ['nothing here.'                  , 'nothing here.'                            , 'stairs going up.', 'a Squirtle.'       ],
            ['stairs going up and a pokeball.', 'a Charmander.'                            , 'a FIRE!!!'       , 'stairs going down.', 'a pokeball.'],
            ['stairs going down.'             , 'a door covered in vines.'                 , '2 pokeballs!'],
            ['your Bulbasaur!!!'              , 'an Eevee with a key tied around its neck.'],
           )

player = {
          'floor': 1,
          'room': 2,
          'pokemons': [],
          'bag': [],
         }

def positionString(player):
    return "floor {p[floor]} room {p[room]}".format(p=player)

def featureString(player):
    return features[player['floor']-1][player['room']-1]

print("You are finally a Pokemon trainer! Today, you have gotten your very first Pokemon, a Bulbasaur!")
name = input("What will you name your Bulbasaur? ")
print("Unfortunately, {} doesn't seem to obey or like you...".format(name))
print("You try to be friendly to {}, but it just won't listen...".format(name))
print("As {} was busy ignoring you, something seems to catch its attention and it runs off!".format(name))
print("You chase after {}, but it's too fast! You see it running into an abandoned Pokeball Factory.".format(name))
print("You must explore the abandoned Pokeball Factory and find {} before something happens to it!".format(name))
print()
print("You may input 'help' to display the commands.")
print()

while gamePlay == True:
    print("You are on {}. You find {}".format(positionString(player), featureString(player)))
    move = input("What would you like to do? ").lower()
    while move not in commands:
        move = input("There's a time and place for everything, but not now! What would you like to do? ").lower()
    if move == 'left':
        if player['room'] > 1:
            player['room'] -= 1
            print("Moved to {}.".format(positionString(player)))
        else:
            print("*Bumping noise* Looks like you can't go that way...")
    elif move == 'right':
        if player['room'] < len(features[player['floor']-1]):
            player['room'] += 1
            print("Moved to {}.".format(positionString(player)))
        else:
            print("*Bumping noise* Looks like you can't go that way...")
    elif move == 'help':
        print("Input 'right' to move right. Input 'left' to move left. Input 'pokemons' to see what Pokemon are on your team. Input 'bag' to see the items you are carrying. Input 'help' to see the commands again.")
    elif move == 'pokemons':
        if len(player['pokemons']) == 0:
            print("There are no Pokemon on your team.")
        else:
            print("The Pokemon on your team are: {}.".format(", ".join(player['pokemons'])))
    elif move == 'bag':
        if len(player['bag']) == 0:
            print("There are no items in your bag.")
        else:
            print("The items in your bag are: {}.".format(", ".join(player['bag'])))
    elif move == 'exit':
        gamePlay = False
    print()

如您所见,我创建了两个函数来从状态向量中获取房间的名称和房间的特征,这样我就不必在任何地方复制这部分代码。其中一个功能是生成字符串本身,因为它们都具有相同的方案:floor X room Y。将它们放在矩阵上是没有意义的,除非你想给它们命名,例如'lobby',如果是这样的话,我让你修改函数的任务,它应该很容易,因为它与第二个非常相似。我还添加了一个“退出”命令来退出循环。

【讨论】:

    【解决方案2】:

    我无法使用提供的代码复制您的错误,因为它引发了另一个错误(列表索引超出范围)

    我怀疑问题出在这里

    currentRoom = [0][1]
    

    这意味着您正在尝试将 currentRoom 的值设置为 [0] 的索引 1,该索引不存在。

    [0] 这里是一个包含一个项目的列表。 如果您对此感到困惑,请启动 python3,然后尝试一下

    currentRoom = [0,2][1]
    print(currentRoom)
    

    根据您的示例,您正在为楼层列表使用嵌套列表。

    floor[0] = 1 楼,floor [0] = 2 楼,以此类推

    在 1 楼,您有另一个列表,其中每个索引确定您当前的房间。

    用两个整数来代替当前位置怎么样?

     currentRoom = 0 // room 1
     currentFloor = 0 //floor 1
     print (You are on floors[currentFloor][currentRoom], you find floorsFeature[currentFloor][currentRoom])
     ....
     ..... // user entered move left
     if currentRoom >0:
          currentRoom -= 1
          print (Moved to floors[currentFloor][currentRoom])
     .... //user went up by one floor
     if ....
          currentFloor += 1
          print (Moved to floors[currentFloor][currentRoom])
    

    【讨论】:

      【解决方案3】:

      你不能定义currentRoom = [0][1]

      >>> currentRoom = [0][1]
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      IndexError: list index out of range
      

      [0][1] 不是整数、字符串或其他类型。您可以使用列表或元组来保存楼层和房间信息:

      #To get floor 3, room 2
      currentRoom = [2,1] # Or you can use currentRoom = (2,1)
      print(floors[currentRoom[0]][currentRoom[1]]) # It refers print(floors[2][1])
      

      输出:

      floor 3 room 2
      

      当你这样做时,可能会出现标题中的错误:

      >>> currentRoom = (2,1)
      >>> print(floors[currentRoom])
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      TypeError: list indices must be integers or slices, not tuple
      

      使用上面的解决方案:

      print(floors[currentRoom[0]][currentRoom[1]])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-02
        • 2019-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-08
        相关资源
        最近更新 更多