【发布时间】:2021-11-03 13:30:34
【问题描述】:
我有一个非常简单的 python 问题,但是我摆弄了一些数字,它仍然不起作用。
import random
import numpy as np
class Room:
def __init__(self, name, contents):
self.name = name
self.contents = contents
rooms = np.zeros((10, 10))
emptyRooms = []
halfHeight = int(len(rooms[1]) / 2)
halfWidth = int(len(rooms[0]) / 2)
rooms[halfWidth][halfHeight] = 1
for r in range(len(rooms)):
for c in range(len(rooms)):
if rooms[r][c] == 1:
if rooms[r][c-1] != 1:
rooms[r][c-1] = 1
if rooms[r][c+1] != 1:
rooms[r][c+1] = 1
if rooms[r-1][c] != 1:
rooms[r-1][c] = 1
if rooms[r+1][c] != 1:
rooms[r+1][c] = 1
print(rooms)
这是输出:
Traceback (most recent call last):
File "main.py", line 27, in <module>
if rooms[r+1][c] != 1:
IndexError: index 10 is out of bounds for axis 0 with size 10
就像我说的,我已经尝试过修改数字,但仍然出现错误。我不知道如何解决它。
【问题讨论】:
-
Python 索引从 0 开始。你的大小是 10。当你的 r 等于 9(最后一个索引)时,r+1 是 10,所以 rooms[r+1] 会导致异常。在大多数其他语言中,您之前会遇到相同的错误 - 使用 c-1 (c==0, c-1==-1 - 但 python 接受负索引 -i 作为 len-i)。
标签: python python-3.x numpy