首页 > 解决方案 > 即使我创建新列表 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 发生了变化。有人可以解释为什么会在嵌套列表中发生这种情况吗?

`

标签: pythonlistnested

解决方案


当您通过[:]它复制列表时,它会执行浅拷贝。这意味着列表的每个元素在复制的版本中保持不变。出于这个原因,子列表本身不会被复制,而是外部列表保留对它们的引用。如果您也想复制子列表,您可以使用copy.deepcopy.


推荐阅读