我在更新包含来自matplotlib的矩形对象的大小为N的列表时遇到问题。我做的是我创建了一个虚拟矩形并创建了一个N个虚拟矩形的列表。然后我想迭代循环来改变每个索引的x,y宽度和高度。第一个循环迭代显示值正在改变,但是当我在第二个循环中迭代相同的列表时,这些值仅显示在第一个循环中的最后一次迭代中保留的属性(下面显示的示例输出)。
以下是我正在处理的代码:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
N = 5
dummyRect = Rectangle((None, None), None, None)
patches = [dummyRect] * N
for i in xrange(N):
x0 = (int(np.random.randint(25, size = 1)))
y0 = (int(np.random.randint(25, size = 1)))
w = (int(np.random.randint(10, size = 1)) + 1) # avoiding zeroes
h = (int(np.random.randint(10, size = 1)) + 1)
print "Index: %s, x0: %s, y0: %s, w: %s, h: %s" % (i, x0, y0, w, h)
patches[i].set_x(x0)
patches[i].set_y(y0)
patches[i].set_width(w)
patches[i].set_height(h)
print "XY:%s, Width: %s, Height: %s" % (patches[i].get_xy(), patches[i].get_width(), patches[i].get_height())
print
print "__________________________________"
for x in patches:
print "XY:%s, Width: %s, Height: %s" % (x.get_xy(), x.get_width(), x.get_height())
输出:
Index: 0, x0: 9, y0: 21, w: 4, h: 3
XY:(9, 21), Width: 4, Height: 3
Index: 1, x0: 9, y0: 24, w: 1, h: 7
XY:(9, 24), Width: 1, Height: 7
Index: 2, x0: 4, y0: 23, w: 7, h: 1
XY:(4, 23), Width: 7, Height: 1
Index: 3, x0: 4, y0: 20, w: 3, h: 9
XY:(4, 20), Width: 3, Height: 9
Index: 4, x0: 2, y0: 13, w: 1, h: 9
XY:(2, 13), Width: 1, Height: 9
__________________________________
XY:(2, 13), Width: 1, Height: 9
XY:(2, 13), Width: 1, Height: 9
XY:(2, 13), Width: 1, Height: 9
XY:(2, 13), Width: 1, Height: 9
XY:(2, 13), Width: 1, Height: 9
如您所见,输出具有第一个循环中最后一次迭代的值。谁知道我在这里做错了什么?相同的概念在Java中可行,我相信但也许不在Python中?
谢谢你的帮助!
答案 0 :(得分:2)
This is almost certainly because your list patches
contains N
copies of the same Rectangle
patch, not independent patches. Try initializing your list with independently-created objects instead of references to the same one:
patches = []
for i in range(N):
patches.append(Rectangle((None, None), None, None))
答案 1 :(得分:1)
you are not creating 5 different rectangles with patches = [dummyRect] * N
, but just 5 references to the same Rectangle
(your dummyRect
)
You could create 5 new instances like this
N=5
patches = [Rectangle((None, None), None, None) for i in range(N)]