尝试修改单个值时,二维列表有奇怪的行为
当我尝试此代码时:
data = [[None]*5]*5
data[0][0] = 'Cell A1'
data
的值最终如下所示:
[['Cell A1', None, None, None, None],
['Cell A1', None, None, None, None],
['Cell A1', None, None, None, None],
['Cell A1', None, None, None, None],
['Cell A1', None, None, None, None]]
为什么 'Cell A1'
值出现在每个嵌套列表中?
When I try this code:
data = [[None]*5]*5
data[0][0] = 'Cell A1'
The value of data
ends up like:
[['Cell A1', None, None, None, None],
['Cell A1', None, None, None, None],
['Cell A1', None, None, None, None],
['Cell A1', None, None, None, None],
['Cell A1', None, None, None, None]]
Why does the 'Cell A1'
value appear in every nested list?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这将创建一个包含五个对相同列表的引用的列表:
使用类似这样的内容来创建五个单独的列表:
现在它的行为符合预期:
This makes a list with five references to the same list:
Use something like this instead which creates five separate lists:
Now it behaves as expected:
正如 中所述序列类型的文档(包括列表):
As explained in the documentation for sequence types (which includes lists):
在 Python 中,每个变量都是一个对象,因此也是一个引用。您首先创建了一个包含 5 个
None
的列表,然后构建了一个包含 5 个相同对象的列表。In Python, every variable is an object, and thus a reference. You first created a list of 5
None
s, and then you build a list with 5 times the same object.