我有一個非常簡單的 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
就像我說的,我試過擺弄數字,但仍然出現錯誤。我不知道如何解決它。
uj5u.com熱心網友回復:
如果要在迭代陣列時使用索引訪問陣列中的下一個元素,則需要迭代到倒數第二個元素。在這里,您正在使用rooms[r][c 1]和rooms[r 1][c]考慮 r 和 c 作為索引。在最后一次迭代中,您的索引超出范圍。因此,在這里您需要將回圈迭代到倒數第二個索引。試試下面的代碼:
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) - 1):
for c in range(len(rooms) - 1):
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)
在這里,我將回圈初始化range(len(rooms) - 1)為range(len(rooms))。我希望它能解決這個問題。
uj5u.com熱心網友回復:
你有 c 1,c 在范圍內(len(房間)):當 c 是最后一個時,c 1 將超出范圍。
uj5u.com熱心網友回復:
您必須檢查 r 1 或 c 1 是否小于 10,因為它試圖索引一個不存在的元素(通常也稱為越界)。
所以在你的代碼中做:
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 (c-1) >= 0 and rooms[r][c-1] != 1:
rooms[r][c-1] = 1
if (c 1) < 10 and rooms[r][c 1] != 1:
rooms[r][c 1] = 1
if (r-1) >= 0 and rooms[r-1][c] != 1:
rooms[r-1][c] = 1
if (r 1) < 10 and rooms[r 1][c] != 1:
rooms[r 1][c] = 1
print(rooms)
確保在向 c 或 r 加 1 的每個位置,結果整數永遠不會大于或等于 10(總是會導致越界錯誤)。
編輯:可能你也不想得到負方向的包裝結果。所以我還添加了對負方向的檢查。(帶有 '(r-1) >= 0' 的部分。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/346964.html
