"列出索引超出范围"在3D对象数组上

时间:2017-01-26 18:44:52

标签: python class multidimensional-array pickle indexoutofrangeexception

我只是试图将一堆块存储在一堆块中。这是一个非常简单的体素世界。目前测试代码中有三个类级别(我将使用pickle模块和序列化):世界,世界中的块和块中的块。

这是追踪:

Traceback (most recent call last):  File "C:/Crayder/Scripts/pickle 
test/pickle1.py", line 27, in <module>    aWorld = world();  File 
"C:/Crayder/Scripts/pickle test/pickle1.py", line 25, in __init__    
self.chunks[cX][cY] = chunk(cX, cY);  File "C:/Crayder/Scripts/pickle 
test/pickle1.py", line 18, in __init__    self.blocks[bX][bY][bZ] = 
block((self.x * 16) + bX, (self.y * 16) + bY, bZ); IndexError: list 
index out of range

以下是代码:

class block:
    def __init__(self, x, y, z, data = 0):
        self.x = x;
        self.y = y;
        self.z = z;
        self.data = data;

class chunk:
    def __init__(self, x, y):
        self.x = x;
        self.y = y;
        self.blocks = [];
        for bX in range(16):
            for bY in range(16):
                for bZ in range(64):
                    self.blocks[bX][bY][bZ] = block((self.x * 16) + bX, (self.y * 16) + bY, bZ);

class world:
    def __init__(self):
        self.chunks = [];
        for cX in range(16):
            for cY in range(16):
                self.chunks[cX][cY] = chunk(cX, cY);

aWorld = world();

print(aWorld.chunks[2][2].blocks[2][2][2]);

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

您正在创建空列表,然后尝试分配它们。您获得的错误与

相同
l = [] 
l[0] = 'something'  # raises IndexError because len(l) == 0

您必须将元素附加到列表中:

l = []
l.append('something')

或预填充列表,以便您可以替换元素:

l = list(range(5))
l[4] = 'last element'

对于你的二维案例:

self.chunks = list(range(16))
for cX in range(16):
    self.chunks[cX] = list(range(16))
    for cY in range(16):
        self.chunks[cX][cY] = chunk(cX, cY)

你可以推断出三维情况。