我写了这段代码:

if __name__ == "__main__" :
    lst = []
    current= []
    for i in range(3):
        print(current)
        print(lst)
        lst.append(current)
        print(lst)
        current.append(i)

我希望它打印:

[]
[]
[[]]
[0]
[[]]
[[],0]
[0,1]
[[],0]
[[],0,[0,1]]

但相反它打印:

[]
[]
[[]]
[0]
[[0]]
[[0], [0]]
[0, 1]
[[0, 1], [0, 1]]
[[0, 1], [0, 1], [0, 1]]

我不明白为什么lst将其成员更改为当前成员。

分析解答

而不是这行lst.append(current),转到这:

from copy import copy

lst.append(copy(current))

这个问题是,当您将current附加到lst时,它看起来很好,但是在下一次迭代中,当您更改当前并再次附加它时,它将更改您已经附加的先前current。这就是为什么你看到两个[0]和三个[0, 1]

请查看这个链接以获得更多说明。

同时阅读This Link将对副本和副本类型产生积极影响。