python : Extend a copy of a list - Bug?

标签 python

<分区>

我正在使用 Python 3.4。
我注意到这种奇怪的行为:

In [1]: a=[1,2,3,4,5,6,7,8,9]
In [2]: b=[10,11,12,13,14,15,16,17,18,19]
In [3]: type(a)
Out[3]: list

In [4]: a
Out[4]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In [5]: b
Out[5]: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

In [6]: c=a
In [7]: c
Out[7]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In [8]: c.extend(b)

In [9]: c
Out[9]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

In [10]: a
Out[10]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

c上的extend方法为什么修改了a
您观察到相同的行为吗?
正常吗?在这种情况下,我如何扩展 c 而使 a 完好无损?

最佳答案

因为在 In [6] 行分配 c 之前,您将 c 设置为 a 一些行。

编辑: 由于我的答案不是那么深,所以请看一下。

您想通过复制a 使c 成为一个新列表。但是有两种复制方式:浅复制深复制

你想要两个单独的列表,所以你需要deepcopy
你不能使用 list() 因为它会浅拷贝你的列表,所以你的两个列表仍然是“连接的”。当您更改一个值时,它也会在另一个列表中更改。
当你使用

c = copy.deepcopy(a)

您将获得两个单独的列表。

关于 python : Extend a copy of a list - Bug?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30657705/

相关文章:

python - 使用 python3 从 urllib 解码字节,有更好的方法吗?

python - 代码检查程序 - Python

python - {% trans "This is the title."%} 是做什么用的,我不明白这个 api

python - pathlib 的 `glob` 方法的顺序在运行之间是否一致?

python - 如何打印递归求值过程?

python - pyautogui Python 3.6 与 ok 按钮交互

python - 获取 SQLAlchemy 中已创建记录的 ID

python - 来自 Docker 的文档 : Could not find a version that satisfies the requirement apturl==0. 5.2(及其他)

python - 通过 tensorflow 输出二维 boolean 掩码值

python - 除以列表数组中的每个值