我一直在尝试将我用 C++ 编写的程序移植到 Python。具体来说,它是一个生成高度图的程序,可以将其导出到 3D 模型,理想情况下,在查看时,高度图看起来像真实的地形。
HeightMap 类包装了一个浮点值的二维数组。现在我将其保留为整数,因为它打印得更好,而且我还没有机会实现任何其他功能。我遇到的问题是,当我调用 set(self, x, y, value) 时,它只是将 x, y 处的值设置为 value,代码为“self.rows[y][x] = value” ,它似乎更改了整个列,访问 self.rows 的每个成员并将该数组的第 x 个成员设置为值。
这是我的代码。我大约 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
最佳答案
你的问题是,当你调用filledArray(initHeight,filledArray(initWidth, 0))
时,第二个参数是通过引用传递的(对于python对象总是这种情况)。在 filledArray
中,您需要为每个数组创建一个 value
副本。这将需要向您的函数添加一些额外的逻辑,类似于:
if type(value) == list:
value = list(value)
或者你可以做稍微少一点的Pythonic:
type(value)(value)
创建副本。
关于Python 二维数组的行为很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9475508/