python - 即使条件不成立,列表值也会在 if 语句内更新

标签 python

我试图扫描矩阵中特定索引 (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/

相关文章:

python - pycurl 和 SSL 证书

python - 平滑二值图像的边缘

python - Pandas 中数据帧的自定义计算函数

python - 如何实现可选的第一个参数(重现 slice() 行为)

python - 'forms.ContactForm 对象'没有属性 'hidden_tag'

python - 类型错误 : '<' not supported between instances of 'SetuptoolsVersion' and 'SetuptoolsVersion'

python - 我可以更新 HDFStore 吗?

python - 在python中复制文件名中包含特定字符串的文件

python - 将文本拆分到关联表时无法显示文本列

python - 在线程等待超时的情况下任意休眠