这部分代码应该检查相邻点是否作为points
列表的一部分存在。
points
列表是给定的。check
列表目前仅检查points
列表的第一项。counted
列表应该显示points
列表中存在的点,这些点与第一个给定点相邻。rowNbr
和colNbr
是给定点相邻的点的以下条件。
points = [[3,2],[4,2],[4,3],[5,2],[5,3],[6,4]]
temp = [[3,2],[4,2],[4,3],[5,2],[5,3],[6,4]]
check = []
counted = []
rowNbr = [1, -1, 0, 0, 1, 1, -1, -1]
colNbr = [0, 0, 1, -1, 1, -1, 1, -1]
check.append(points[0])
for j in range(len(check)):
for i in range(len(rowNbr)):
temp[j][0] = check[j][0] + rowNbr[i]
temp[j][1] = check[j][1] + colNbr[i]
if temp[j] in points:
counted.append(temp[:])
print(counted)
我希望它打印:[[4, 2], [4, 3]]
它打印出以下内容:
[[[2, 1], [4, 2], [4, 3], [5, 2], [5, 3], [6, 4]], [[2, 1], [4, 2], [4, 3], [5, 2], [5, 3], [6, 4]]]
如果我在if temp[j] in points:
循环中包含一条print(temp[j])
线,它会打印 corect 坐标,但counted
列表是错误的,并打印出所有内容。
为什么会发生此错误以及如何解决它?
counted.append(temp[:])
每次执行时都会附加整个 temp 数组的副本——如果你只想让它附加一个 temp[j] 的副本,请改为counted.append(temp[j][:])
。
我认为您在对temp[:]
的引用中缺少一个元素(应该是counted.append(temp[j][:])
而不是counted.append(temp[:])
:
points = [[3,2],[4,2],[4,3],[5,2],[5,3],[6,4]]
temp = [[3,2],[4,2],[4,3],[5,2],[5,3],[6,4]]
check = []
counted = []
rowNbr = [1, -1, 0, 0, 1, 1, -1, -1]
colNbr = [0, 0, 1, -1, 1, -1, 1, -1]
check.append(points[0])
for j in range(len(check)):
for i in range(len(rowNbr)):
temp[j][0] = check[j][0] + rowNbr[i]
temp[j][1] = check[j][1] + colNbr[i]
if temp[j] in points:
counted.append(temp[j][:])
print(counted)