“列表索引必须是整数或切片,而不是元组”错误

新手上路,请多包涵

我是编码初学者,目前正在制作角色扮演游戏。当我运行代码时,它给了我上述错误。给我错误的部分是 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()

原文由 Adilene 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
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])

原文由 elanor 发布,翻译遵循 CC BY-SA 3.0 许可协议

让我们按部分进行:

提供所有需要的代码:

我们不知道 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

As you can see I’ve used different values ( int and str ) and different containers ( list , set , tuple , str , …) 我可以使用更多。使用 not in 给出与预期相反的答案。在您的情况下,您可以使用:

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

字符串格式:

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

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

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

list s 和 tuple s:

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

dict s

dict s 是保持状态的好方法:

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

您不必存储数组的长度:

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

多维列表(又名矩阵):

您似乎在处理矩阵时遇到了一些问题,请使用以下表示法: matrix[i][j] 访问 j+1 i+1 第一个元素(从 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' 之类的名称,如果是这样的话,我让你修改函数的任务,它应该很容易,因为它非常类似于第二个。我还添加了一个“退出”命令来退出循环。

原文由 Adirio 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题