简体   繁体   中英

IndexError: list index is out of range

Here is my code for part of my "Hunt the Wumpus (WAMPA)" game. It works if I make the range (0,20), but if I do (1,21) so there are still 20 caves, but no "Cave number 0"...which is just me being finnicky...and it tells me that the list index is out of range...not sure why moving everything up one digit in my range would do this, as there is no direct reference to a specific number in that range anywhere else...so removing 0 shouldn't be an issue, but alas...it is...here is the code where the error is from:

from random import choice

cave_numbers = range(1,21)
caves = []
for i in cave_numbers:
    caves.append([])

for i in cave_numbers:
    for j in range(3):
        passage_to = choice(cave_numbers)
        caves[i].append(passage_to)

And here is the code in its entirety, just for completion's sake:

from random import choice

cave_numbers = range(1,21)
caves = []
for i in cave_numbers:
    caves.append([])

for i in cave_numbers:
    for j in range(3):
        passage_to = choice(cave_numbers)
        caves[i].append(passage_to)


wampa_location = choice(cave_numbers)
wampa_friend_location = choice(cave_numbers)
player_location = choice(cave_numbers)
while (player_location == wampa_location or player_location == wampa_friend_location):
    player_location = choice(cave_numbers)

print("Welcome to Hunt the Wampa!")
print("You can see", len(cave_numbers), "caves.")
print("To play, just type the number")
print("of the save you wish to enter next.")

player_location != wampa_location

while True:
    if player_location != wampa_location:
        print("You are in cave", player_location)
        print("From here, you can see caves:", caves[player_location])
        if(player_location == wampa_location -1 or player_location == wampa_location +1):
              print("I smell a Wampa!")
        if(player_location == wampa_friend_location -1 or player_location == wampa_friend_location +1):
        print("I smell a stinky Wampa!")
    print("Which cave next?")
    player_input = input(">")
    if(not player_input.isdigit() or
             int(player_input) not in caves[player_location]):
          print(player_input, "isn't a cave you can see from here!")
    else:
          player_location = int(player_input)
          if player_location == wampa_location:
              print("Aargh! You got eaten by a Wampa!")
          if player_location == wampa_friend_location:
              print("Aargh! You got eaten by the Wampa's friend!")

I apologize if the indenting is bad on that, some of the lines wrap and I lost my place...but I think the error is in those first 11 lines anyway.

Thanks guys

你的缩进很好,但你需要把 (0, 20) 因为实际发生的是当你在那里追加时它没有定义每个洞穴 [int] 去什么,如果你要使用字典,这将是完全可能的,但结果是你最终得到了caves = [[]*20]所以当你for i in cave_numbersfor i in cave_numbers它试图从1 开始到20,但由于python 是从零开始的,当你到达时它会引发错误20 因为caves实际上从 0 开始,一直到 19,这仍然是 20 条数据。

for i in cave_numbers:
    for j in range(3):
        passage_to = choice(cave_numbers)
        caves[i].append(passage_to)

This takes each number in the range 1..20 and tries to use it as an index into a list of length 20, getting caves number 2, 3, ... 20. When it gets to i = 20, it finds that there is no element in the list with that index, and dies.

Changing the range from (0,20) to (1,21) does not change the size of the resulting list as you would expect. The length stays at 20.

However, because you are using the values in your range list as indexes, your final index is too high. There is no caves[20] because that would need a list of 21 elements, and your list has only 20 elements (in both cases).

Maybe you want something like this? (tested)

#!/usr/local/cpython-3.3/bin/python

from random import choice

cave_numbers = range(1,21)
caves = []
for i in cave_numbers:
    caves.append([])

for index, cave in enumerate(caves):
    for j in range(3):
        passage_to = choice(cave_numbers)
        cave.append(passage_to)

Let me try to break down the issue for you:

Explanation

First of all let us examine the first few lines:

cave_numbers = range(1,21)
caves = []
for i in cave_numbers:
    caves.append([])

If we keep track of the 'memory' it would look like this:

cave_numbers = iterator
list(cave_numbers) = [1,2,3,4,5,...,20]
caves = [[],[],[],[],[],....,[]]

The part that gives you trouble happens right here. As you can see the cave_numbers go from 1 to 20 and your caves array has exactly 20 empty lists in it, but arrays in python are zero indexed. Meaning the first element is in the array is actually at position zero. Here is a quick example of what that means and what happens in your program:

my_indices = [1,2,3,4,5]
my_list = [1,2,3,4,5]
print(f'{my_list[0]}')  # print out '1'
for i in my_indices:
  print(f'{my_list[i]}')  # print out '234' ... and then a index out of exception happens

The index out of bound exception here happens because you are using 5 as an index for an array that has its bound set to [0,4] .

The following code snippet actually produces this exact problem:

for i in cave_numbers:
    for j in range(3):
        passage_to = choice(cave_numbers)
        caves[i].append(passage_to)  # here i will be substituted for '1' to 20'

When you access caves[20] the an exception is thrown because the bound of this array are actually [0, 19] .

How to fix it?

The easiest way is to probably always start your range from zero to N . Zero indexing is (for the most part) the norm in programming and you should get used to it. When any user interaction is required that contains the index just add '1', as seen below:

print(f'You are in cave {player_location + 1}')

In essence the user does not care how you index your array in your code but you are right to not show the user that it is zero indexed (because it might be confusing).

A tip:

print('some text', variable) is really old school - try out f-strings in python 3 (eg: print(f'some text {variable}') )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM