所以我在python中遇到了一个奇怪的问题。我正在使用下面的代码创建对象所在位置的绘图。这是我的密码:
def GoForward(self, duration):
if (self.TowardsX - self.X == 0):
Myro.robot.motors(self.Speed, self.Speed)
Myro.wait(abs(duration))
Myro.robot.stop()
#get the amount of points forward
divisible = (int) (duration / self.Scale)
#add them to the direction
self.TowardsY += divisible
tempY = self.Y
for y in xrange(self.Y, divisible + tempY):
if (y % self.Scale == 0):
self.Plot[(int) (self.X)][y] = 1
return
#calc slope
slope = (self.TowardsY - self.Y) / (self.TowardsX - self.X)
tempX = self.X
tempY = self.Y
#go forward
#get the amount of points forward
divisible = duration / self.Scale
#add them to the direction
self.TowardsX += divisible
self.TowardsY += divisible
Xs = []
Ys = []
for x in xrange(self.X, tempX + divisible):
#find out if it is a plottable point
if (((slope * (x - self.X)) + self.Y) % self.Scale == 0.0):
Xs.append(x)
Ys.append((int)((slope * (x - self.X)) + self.Y))
#Plot the points
for i in xrange(0, len(Xs)):
for j in xrange(0, len(Ys)):
if (self.Plot[Xs[i]][Ys[j]] == 0):
self.Plot[Xs[i]][Ys[j]] = 1
self.X += divisible
self.Y += divisible
但是,当我调用GoForward(2)
时,它用1填充五列,而不是几个点。示例:
[[0,0,0,0,1,1,0,0,0,0]
[0,0,0,0,1,1,0,0,0,0]
[0,0,0,0,1,1,0,0,0,0]
[0,0,0,0,1,1,0,0,0,0]
[0,0,0,0,1,1,0,0,0,0]
[0,0,0,0,1,1,0,0,0,0]
[0,0,0,0,1,1,0,0,0,0]
[0,0,0,0,1,1,0,0,0,0]
[0,0,0,0,1,1,0,0,0,0]
[0,0,0,0,1,1,0,0,0,0]]
基于给GoForward(n)
的参数,它创建了许多充满0的列。。。为什么会发生这种行为?我的代码不应该产生这种效果,但我对python缺乏经验,这就是为什么会发生这种情况?提前谢谢
编辑
所以我把绘制点的代码改成了
for i in xrange(0, len(Xs)):
if (self.Plot[Xs[i]][Ys[i]] == 0):
self.Plot[Xs[i]][Ys[i]] = 1
它将具有正确的值,但是它仍然产生这种奇怪的行为,问题在于这里的代码。你知道吗
编辑2
当我使用代码时:
self.Plot[3][3] = 1
它仍然会生成一个数组:
[[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]]
所以要生成您显示的网格,您正在打印
self.Plot
?你说这个网格被初始化为0?什么是self.Plot
?一张单子,就这样?当您在运行循环之前打印self.Plot
时,它是否打印您所期望的内容(我假设应该都是零)?你知道吗因此,如果
Xs
和Ys
是应该为1的点,您可以将代码简化为使用一个可绘制点列表:我不确定
self.Plot
是如何被初始化或使用的,但是如果你在每一步之前和之后打印东西,你应该能够找出你的逻辑哪里是错误的。你知道吗编辑1: 额外的小Python提示:
与我的第一个代码示例执行的操作相同,但是使用了变量。你知道吗
编辑2:
问题实际上是如何初始化
self.Plot
。当你重复这样一个列表时,你的外部列表就变成了一个指针列表…所有指针都指向同一个对象(在本例中是一个列表)。所以当你说self.Plot[3][3] = 1
时,实际上是在每一行中设置该列。尝试用这样的方法初始化self.Plot
(可能有更好的方法,但我累了):我想说在做任何修改之前,您应该先做一个简单的导入(来自未来的导入部门)。对我来说,问题似乎在于分工。在Python2.7中,它返回一个整数。 看看这个:
但是如果你导入新的部门功能。。。你知道吗
相关问题 更多 >
编程相关推荐