【问题标题】:Why is append() function changing value of variable in every iteration?为什么 append() 函数在每次迭代中都会改变变量的值?
【发布时间】:2020-03-17 06:23:38
【问题描述】:

这是我的代码。

print("enter string")
s=[int(i) for i in input().split()]
r=s.copy()

n=[' ',' ',' ']
d=[]

def rep(index):
    temp=[]
    for i in range(3):
        if(s[index-i-1] not in temp):
            temp.append(s[index-i-1])
    if(len(temp)!=3):
        temp.append(s[index-4])
    return temp[-1]

for i in range(len(s)):
    if(i<3):
        n[i]=s[i]
        print(s[i])
        print(n)
        d.append(n)
        print(d)
    elif(s[i] in n):
        print(s[i])
        print(n)
        d.append(n)
        print(d)
        continue
    else:
        n[n.index(rep(i))]=s[i]
        print(s[i])
        print(n)
        d.append(n)
        print(d)
print(d)

list n 的值根据 LRU 发生变化,并且该列表被附加到 list d 中,但 append 函数在每次迭代中都会更改列表 d。有人能告诉我如何避免这种情况吗?

【问题讨论】:

    标签: python-3.x lru


    【解决方案1】:

    当您将list n 附加到list d 时,您现在有两种方法可以访问您的列表。通过您的变量 (n) 和 list d (d[index])。两者都指向内存中的同一个列表对象。因此,当您以一种方式(n[index] = value)更改列表 n 时,当您查看 list d 内部时也会看到更改。

    要解决它,不要将list n 附加到list d,而是将list n 的副本附加到list d

    将所有d.append(n) 替换为d.append(n.copy())

    【讨论】:

    • 这解决了问题,虽然更改列表 n 不应该更改列表 d,为什么会发生这种情况?
    • @Athena 我已经用解释更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2015-05-18
    • 2021-03-18
    相关资源
    最近更新 更多