即使条件不是tru,if语句中的列表值也会更新

2024-09-30 06:20:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图扫描矩阵中特定索引(firstCord)的八个相邻索引,并找出它的任何相邻索引是否存在于另一个包含一些随机坐标作为元素的列表(Cord)中。如果它的任何一个邻居出现在Cord列表中,那么我将把这个特定的坐标附加到Temp_Cord列表中。下面给出了代码片段。你知道吗

我可以看到,当if newCord in Cord:条件第一次满足时,Temp_Cord会被附加上newCord值。这是预期的行为。但是Temp_Cord中的附加值在每隔一次迭代中根据newCord中的变化而变化,这就像Temp_Cord[0]newCord共享相同的内存一样。有人能帮我解决这个问题吗。只有当if newCord in Cord:条件为真时,我才需要用newCord值附加Temp_Cord。你知道吗

提前谢谢。你知道吗

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) 

Tags: 代码in元素列表lenif矩阵条件
1条回答
网友
1楼 · 发布于 2024-09-30 06:20:54

你在一次又一次地追加相同的列表

为什么不用这样的tuple?你知道吗

for i in orientation:
    newCord = firstCord[0] + i[0], firstCord[1] + i[1]

或者如果它需要是一个list-每次都要做一个新的

for i in orientation:
    newCord = [firstCord[0] + i[0], firstCord[1] + i[1]]

相关问题 更多 >

    热门问题