python - 即使我创建新列表 Python,嵌套列表变量也会发生变化
问题描述
当我只有一个常规列表并且想要复制此列表而不更改另一个列表时:
sent1=['The', 'dog', 'gave', 'John', 'the', 'newspaper']
sent2 = sent1[:]
sent1[1] = 'monkey'
sent2
['the', 'dog', 'gave', 'John', 'the', 'newspaper']
我们可以看到 sent2 没有改变。但是,当我有一个嵌套列表时,例如
text1=[['The', 'dog', 'gave', 'John', 'the', 'newspaper'], ['John', 'is', 'happy']]
text2 = text1[:]
text1[0][1] = 'monkey'
text2
[['The', 'monkey', 'gave', 'John', 'the', 'newspaper'], ['John', 'is', 'happy']]
我们看到 sent2 发生了变化。有人可以解释为什么会在嵌套列表中发生这种情况吗?
`
解决方案
当您通过[:]
它复制列表时,它会执行浅拷贝。这意味着列表的每个元素在复制的版本中保持不变。出于这个原因,子列表本身不会被复制,而是外部列表保留对它们的引用。如果您也想复制子列表,您可以使用copy.deepcopy
.
推荐阅读
- assembly - 在 32 位 Mips 架构中,如果内存只有 32 位长地址,为什么加载字指令需要立即偏移?
- python - Python Click:如何为全局上下文更改 `info_name` 的值
- python - 从 csv 文件中读取特定列
- swift - SwiftUI - 无法在 Firebase 的 observeSingleEvent 内分配变量。返回零
- nuget - 依赖项中的 Nuget 包冲突
- javascript - 解析(输入)为 JSON 字符串
- ruby-on-rails - 使用基于 API 密钥的身份验证时使用的正确标头是什么
- android - mvvm 使用 dagger2 和 ViewModelFactory,不理解默认注入
- cython - 如果有同名的属性,Cython 不能引用 cdef 类中的声明类型?
- docker - Docker BuildKit 是否被认为是稳定的/生产友好的?