我试图扫描矩阵中特定索引 (firstCord
) 的八个相邻索引,并查找其邻居是否存在于另一个列表 (Cord
) 中包含一些随机坐标作为元素。如果它的任何邻居出现在 Cord
列表中,那么我会将该特定坐标附加到 Temp_Cord
列表中。代码片段如下。
当第一次满足 if newCord in Cord:
条件时,我可以看到 Temp_Cord
附加了 newCord
值。这是预期的行为。但是 Temp_Cord
中的附加值在每隔一次迭代中都会根据 newCord
的变化而变化,这就像 Temp_Cord[0]
和 newCord
共享相同的内存。有人可以帮我解决这个问题吗?仅当 if newCord in Cord:
条件为 true 时,我才需要在 Temp_Cord
后面附加 newCord
值。
提前致谢。
Cordlen = len(Cord)
orientation = [(-1,0), (-1,1), (0,1), (1,1), (1,0), (1,-1),(0,-1),(-1,-1)]
firstCord = [0,173]
Temp_Cord = []
while ((Arrlen) < Cordlen):
newCord = [0,0]
for i in orientation:
newCord[0] = firstCord[0] + i[0]
newCord[1] = firstCord[1] + i[1]
if newCord in Cord:
Temp_Cord.append(newCord)
Arrlen = len (Temp_Cord)
最佳答案
您一遍又一遍地附加相同列表
为什么不直接使用这样的元组
?
for i in orientation:
newCord = firstCord[0] + i[0], firstCord[1] + i[1]
或者如果它需要是一个列表
- 每次创建一个新列表
for i in orientation:
newCord = [firstCord[0] + i[0], firstCord[1] + i[1]]
关于python - 即使条件不成立,列表值也会在 if 语句内更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20558967/