关于python,一个奇怪的问题,望高手解答有如下一段程序:Python codet []st []ki 0st.append([ki,t])w
关于python,一个奇怪的问题,望高手解答
有如下一段程序:
Python codet = []st = []ki = 0st.append([ki,t])while ki < 5: ki = ki+1 t.append(ki+1) star =[ki,t] st.append(star) print(st)
程序输出为:
[[0, [2]], [1, [2]]]
[[0, [2, 3]], [1, [2, 3]], [2, [2, 3]]]
[[0, [2, 3, 4]], [1, [2, 3, 4]], [2, [2, 3, 4]], [3, [2, 3, 4]]]
[[0, [2, 3, 4, 5]], [1, [2, 3, 4, 5]], [2, [2, 3, 4, 5]], [3, [2, 3, 4, 5]], [4, [2, 3, 4, 5]]]
[[0, [2, 3, 4, 5, 6]], [1, [2, 3, 4, 5, 6]], [2, [2, 3, 4, 5, 6]], [3, [2, 3, 4, 5, 6]], [4, [2, 3, 4, 5, 6]], [5, [2, 3, 4, 5, 6]]]
我本意是想让其输出:
[[0, []], [1, [2]]]
[[0, []], [1, [2]], [2, [2, 3]]]
[[0, []], [1, [2]], [2, [2, 3]], [3, [2, 3, 4]]]
[[0, []], [1, [2]], [2, [2, 3]], [3, [2, 3, 4]], [4, [2, 3, 4, 5]]]
[[0, []], [1, [2]], [2, [2, 3]], [3, [2, 3, 4]], [4, [2, 3, 4, 5]]], [5, [2, 3, 4, 5, 6]]]
让我觉得诡异的是,对t的修改,竟然会改变st中已有的原通过t赋值的部分,这是怎么回事啊,请高手大侠赐教。。。
[解决办法]star = [ki, t], star中保存的是一个指向t的reference.
要达到你要的效果, 可以这样:
star = [ki, t[:]] # star中会保存一份t的copy