Python 二维数组表现异常

2024-09-30 23:30:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直试图把我用C++编写的程序移植到Python。具体来说,它是一个生成高度图的程序,可以导出到三维模型中,理想情况下,它看起来像真实的地形。在

HeightMap类包装了一个二维的浮点值数组。现在我把它保存为整数,因为它打印得更好,而且我没有机会实现任何其他特性。我遇到的问题是,当我调用set(self,x,y,value)时,它只是用代码将x,y的值设置为value”self.行[y] [x]=value”,它似乎改变了整个列,访问了self.行并将该数组的第x个成员设置为value。在

这是我的密码。我有90%的把握错误出在2数组的初始化中。在

def filledArray(length, value) :
    result = []
    for i in range(1, length) :
        result.append(value)
    return result

def resizeArray(array, newLength, nullValue) :
    if newLength == len(array) :
        return array
    result = []
    for i in range(0, newLength) :
        if i < len(array) :
            result.append(array[i])
        else :
            result.append(nullValue)
    return result

class HeightMap:
    """A class that wraps a 2D array for generating height maps"""
    def __init__(self) :
        self.width = 0
        self.height = 0
        self.rows = []

    def __init__(self, initWidth, initHeight) :
        self.clear(initWidth, initHeight);

    def clear(self, initWidth, initHeight) :
        self.width = initWidth
        self.height = initHeight
        self.rows = filledArray(initHeight, filledArray(initWidth, 0))

    def setHeight(self, newHeight) :
        if self.height == newHeight :
            return
        self.rows = resizeArray(self.rows, newHeight, filledArray(self.width, 0))

    def setWidth(self, newWidth) :
        if self.width == newWidth :
            return
        for i in range(0, len(self.rows)) :
            self.rows[i] = resizeArray(self.rows[i], newWidth, 0);
        self.width = newWidth

    def get(self, x, y) :
        return self.rows[y][x]

    def set(self, x, y, value) :
        self.rows[y][x] = value

    def add(self, x, y, value) :
        self.rows[y][x] += value

    def multiply(self, x, y, value) :
        self.rows[y][x] *= value

Tags: selfforreturnifvaluedefresultwidth
1条回答
网友
1楼 · 发布于 2024-09-30 23:30:38

您的问题是,当您调用filledArray(initHeight, filledArray(initWidth, 0))时,第二个参数是通过引用传递的(python对象总是这样)。在filledArray中,您需要为每个文件制作一个value的副本。这将需要在您的函数中添加一些附加逻辑,大致如下:

if type(value) == list:
   value = list(value)

或者你可以做一个稍微少一点的Python:

^{pr2}$

创建副本。在

相关问题 更多 >