【问题标题】:Adding elements to a 3d array in python在python中将元素添加到3d数组
【发布时间】:2014-12-21 03:42:51
【问题描述】:

我是 Python 新手,我正在尝试将元素添加到 3D 列表中。

def getHoughSpace(self):
        space = [[[]]]
        for i in range(0, len(self.xs)):
            rho = self.getRho(self.xs[i], self.ys[i], self.zs[i])
            space.append([Cell(rho, 0)])
            for j in range(0, len(self.ys)):
                theta = self.getTheta(self.xs[j], self.ys[j], self.zs[j])
                space[i].append([Cell(theta, 0)])
                for k in range(0, len(self.zs)):
                    phi = self.getPhi(self.xs[k], self.ys[k])
                    space[i][j].append([Cell(phi, 0)]) # error happens here

但是,当i=1、j=0 和k=0 时,我的程序崩溃并出现以下错误:

AttributeError: Cell instance has no attribute 'append'

为什么会这样?我怎样才能通过i=0、j=0 和k=0 而不是当i=1?显然,我正在访问space[i][j] 的单元格,但我想访问Cells 的列表。

  • 有趣的一点是,如果我注释掉错误行,它就会运行。那么为什么问题只出现在第三维呢?

【问题讨论】:

    标签: python arrays list multidimensional-array


    【解决方案1】:

    对于三维列表,您可能希望在末尾附加元素:

    space = []
    space.append([])
    space[i].append([])
    space[i][j].append(<element>)
    

    或者你可以使用numpy:

    import numpy as np
    space = np.empty((len(self.xs), len(self.ys), len(self.zs)), dtype=object)
    

    【讨论】:

    • 我用 numpy 让它工作。我会注意到你不能再使用 append ,因为你已经分配了一个数组。您必须使用space[i][j][k] = Cell(phi, 0)。
    • @TrevorHutto 原始程序的问题是:space.append([Cell(rho, 0)]),它扰乱了列表的维度,如果你打印它,你可以看到另一个list被添加为元素而不是list of list。
    猜你喜欢
    • 2022-06-10
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 2020-03-16
    • 2014-07-23
    相关资源
    最近更新 更多