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

时间:2017-10-31 02:58:16

标签: python python-3.x

我是编码的初学者,我目前正在制作一个RPG。当我运行代码时,它给了我上面的错误。给我错误的部分是print("You are on " + floors[currentRoom] + ". You find " + floorsFeature[currentRoom])。我的猜测是地板,地板特征和当前房间一定有问题。因为我是初学者,所以我不确定错误的含义。有人可以用简单的语言解释一下吗?

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()

3 个答案:

答案 0 :(得分:0)

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

我怀疑问题在这里

currentRoom = [0][1]

这意味着你试图将currentRoom的值设置为[0]的索引1,这是不存在的。

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

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

根据您的示例,您使用的是嵌套列表。

floor [0] = floor 1,floor [0] = floor 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])

答案 1 :(得分:0)

您无法定义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]])

答案 2 :(得分: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

正如您所看到的,我使用了不同的值(intstr)和不同的容器(listsettuple,{{ 1}},...)我可以使用更多。使用str会给出与预期相反的答案。在您的情况下,您可以使用:

not in

字符串格式化:

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

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

基本上你使用由print("Unfortunately, {} doesn't seem to obey or like you...".format(name)) 分隔的placehodlers,然后使用你想放在那里的参数调用{}函数。在.format()内,您可以放置​​不同的附加字符串来格式化输出,例如确定浮点数的小数位数。

{}list s:

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

tupleŠ

dict是保持状态的好方法:

dict

您不必存储数组的长度:

在某些语言中,您始终会保留数组中的项目数量。 Python的容器可以通过调用player = { 'floor': 1, 'room': 2, 'pokemons': [], 'bag': [], } 在运行时确定它们的大小。您已在代码的某些部分使用它,但保留了不需要的len(container)count个变量。

多维列表(a.k.a.matrixes):

您似乎在处理矩阵时遇到一些问题,请使用以下表示法:countItems来访问matrix[i][j]列表中的j+1元素(因为它从0开始)

i+1

要了解列表的数量,请在您的案例中使用matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ] print(matrix[1][2]) # Output: 6 。要知道第n个列表的元素数量,请使用len(matrix)

最终代码:

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,我告诉你修改函数的任务,如果是这样的话,它应该很容易,因为它会非常类似于第二个一。我还添加了一个'exit'命令来退出循环。