python - 更改列表的元素会影响/不影响派生列表

标签 python list element immutability mutability

我不理解 Python 中列表的以下异常行为,如果有人能提供一些线索,我将不胜感激:

片段 1:

myList = [1,2,3,4]
A = [myList]*3
print(A)
myList[2]=45
print(A)

输出:

[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
[[1, 2, 45, 4], [1, 2, 45, 4], [1, 2, 45, 4]]

这对我来说很有意义,因为我们没有执行额外的复制函数来“屏蔽”A 免受 myList 上的元素操作的影响。

片段 2:

myList = [1,2,3,4]
A = myList*3
print(A)
myList[2]=45
print(A)

输出:

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

为什么对 myList 的更改没有反射(reflect)在 A 中?

最佳答案

在第一种情况下,您直接复制 3 个对 myList 的引用。在第二种情况下,您复制了对 myList内容 的 3 个引用,这使您与原始 myList 没有任何连接。

关于python - 更改列表的元素会影响/不影响派生列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33193934/

相关文章:

python - 如何使用pyspark计算出现次数

python - 重叠片段

jsf - 如何在JSF panelGrid中添加一个空元素?

python - GmailAPI : "Error sending test message to Cloud PubSub projects/[project-id]/topics/[topic-id] : User not authorized to perform this action."?

python - 在桌面应用程序中运行嵌入式 Web 服务器的推荐方式是什么(比如带有 pyqt 的 wsgi 服务器)

python - 将从 scrapy 中抓取的数据放入 elasticsearch 时出现 TypeError

python - 在每个 for 循环迭代中遍历列表

c++ - 如何在没有 'new' 的情况下将新对象实例添加到 std::list

css - 如何删除css中的element.style

arrays - 如何使用 Jolt 将 n 个对象的 json 数组展平?