gpt4 book ai didi

python - 创建包含零的列表时出现意外行为

转载 作者:太空宇宙 更新时间:2023-11-03 21:44:51 24 4
gpt4 key购买 nike

考虑Python解释器3.6中的以下两段代码-

>>> d = {0:[[1,2],[3,4]]}
>>> d[1] = [[0]*2]*2
>>> d
{0: [[1, 2], [3, 4]], 1: [[0, 0], [0, 0]]}
>>> d[1][0][0] = 5
>>> d
{0: [[1, 2], [3, 4]], 1: [[5, 0], [5, 0]]}

 >>> d = {0:[[1,2],[3,4]] , 1 : [[0,0],[0,0]]}
>>> d
{0: [[1, 2], [3, 4]], 1: [[0, 0], [0, 0]]}
>>> d[1][0][0] = 5
>>> d
{0: [[1, 2], [3, 4]], 1: [[5, 0], [0, 0]]}

为什么他们给出不同的 d[1] 值唯一的区别是什么时候零列表的创建方式?

最佳答案

>>> d = {0:[[1,2],[3,4]]}
>>> d[1] = [[0]*2]*2 #You are using the same address of the list to create the second list
>>> d
{0: [[1, 2], [3, 4]], 1: [[0, 0], [0, 0]]}
>>> d[1][0][0] = 5
>>> d
{0: [[1, 2], [3, 4]], 1: [[5, 0], [5, 0]]}

因此,如果更改一个内存地址的值,另一个内存地址的值也会发生变化。

>>> d = {0:[[1,2],[3,4]]}
>>> d[1] = [[0]*2,[0]*2] #Now we are creating two list of different address
>>> d
{0: [[1, 2], [3, 4]], 1: [[0, 0], [0, 0]]}
>>> d[1][0][0] = 5
>>> d
{0: [[1, 2], [3, 4]], 1: [[5, 0], [0, 0]]}

在上面的代码中你可以感受到差异。您问题的答案是内存地址就是原因。

编辑:

它适用于任何值,而不仅仅是零

关于python - 创建包含零的列表时出现意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52574880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com