【问题标题】:"List index out of range" on 3D array of objects3D对象数组上的“列表索引超出范围”
【发布时间】:2017-01-26 18:44:51
【问题描述】:

我只是想将一堆块存储在一堆块中。这是一个非常简单的体素世界。目前测试代码中有三个类级别(我打算玩一下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]);

我在这里做错了什么?

【问题讨论】:

  • 您使用的是list,而不是数组。

标签: python class multidimensional-array pickle indexoutofrangeexception


【解决方案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)

您可以将其外推到三维情况。

【讨论】:

  • 这是正确的,但我使用的是 Python 3.5.2。 range 函数从字面上返回一个“范围”可迭代对象。所以对于那些使用 3+ 的人,使用列表类(即,而不是 range(16) 使用 list(range(16)))。
  • 你说得对(我用的是 2.7)。编辑后的答案(使用列表推导而不是 list())。
猜你喜欢
  • 1970-01-01
  • 2018-08-18
  • 2023-03-16
  • 1970-01-01
  • 2021-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-16
相关资源
最近更新 更多