有人有一個想法,爲什麼我在這段代碼中得到一個IndexError?IndexError:列表分配索引超出範圍Python 3
global gegner
global gegnerhp
gegner = []
gegberhp = []
for i in range(1,anzahlgegner):
random = randint(1,5)
if random == 1:
gegner[i] = "goblin"
gegnerhp[i] = randint(10,50)
elif random == 2:
gegner[i] = "ghost"
gegnerhp[i] = randint(10,50)
elif random == 3:
gegner[i] = "hound"
gegnerhp[i] = randint(10,50)
elif random == 4:
gegner[i] = "wolf" #LINE 147
gegnerhp[i] = randint(10,50)
elif random == 5:
gegner[i] = "goblin"
gegnerhp[i] = randint(10, 50)
print("* {0} with {1} HP".format(gegner[i]),gegnerhp[i])
例如,當隨機爲4我得到以下錯誤:
File "C:/Users/Fabio/PycharmProjects/test\dungeon.py", line 147, in run
gegner[i] = "wolf"
IndexError: list assignment index out of range
也許我的列表/陣列的聲明是錯誤的...
他們必須已滿?但如果我需要它們像這樣的情況下,我該怎麼辦? – zwerg4
@ zwerg4使用'lst.append(element)'將項目添加到列表'' –