簡體   English   中英

“列表索引必須是整數或切片,而不是元組”錯誤

[英]"List indices must be integers or slices, not tuple" error

我是編碼初學者,目前正在制作 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()

讓我們分部分說:

提供所有需要的代碼:

我們不知道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:
    ...

字符串格式:

有多種格式化字符串以在其中包含變量值的方法,但最str.format()方法是使用str.format() 您可以在 此處查看有關格式化字符串如何工作的文檔,但最簡單的示例是:

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

基本上,您使用由{}分隔的占位符,然后使用要放置在那里的參數調用.format()函數。 {}內,您可以放置​​不同的附加字符串來格式化輸出,例如確定浮點數的小數位數。

listtuple

Python 中的listtuple都是序列容器。 主要區別在於list是可變的,而tuple不是。 它們都使用從0開始的var[position]符號訪問。 所以如果你不打算改變一個序列的內容,你應該使用tuple而不是列表來強制解釋器並提高內存效率。 元組使用括號而不是方括號。

dict

dict是保持狀態的好方法:

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

您不必存儲數組的長度:

在某些語言中,您總是將項目的數量保存在一個數組中。 Python 的容器可以在運行時通過調用len(container)來確定它們的大小。 您已經在代碼的某些部分使用了它,但是您保留了一個不需要的countcountItems變量。

多維列表(又名矩陣):

您似乎在處理矩陣時遇到了一些問題,請使用以下符號: matrix[i][j]訪問第i+1個列表的第j+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' ,如果是這種情況,我會讓你修改函數的任務,它應該很容易,因為它與第二個非常相似。 我還添加了一個“退出”命令以退出循環。

我無法使用提供的代碼復制您的錯誤,因為它引發了另一個錯誤(列表索引超出范圍)

我懷疑問題出在這里

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

您不能定義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]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM