python嵌套列表意外行为 [英] python nested list unexpected behaviour

查看:80
本文介绍了python嵌套列表意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中使用嵌套列表时,我遇到了意外的行为,这花了一些时间进行调试.如果列表是这样初始化的:

I've ran into an unexpected behavior when using a nested list in python, that took a while to debug. If a list is initialized like this:

a = [[None] * 2] * 2
a
[[None, None], [None, None]]

和另一个初始化如下的列表:

and another list initialized like this:

b = [[None, None], [None, None]]
b
[[None, None], [None, None]]

我期望这两个列表具有相同的行为,但如果这样做:

I would expect the same behavior from both these lists, but if I do:

a[0][0] = 3
a
[[3, None], [3, None]]

如果我这样做:

b[0][0] = 3
b
[[3, None], [None, None]]

有人可以解释这种情况发生的原因吗?谢谢

Can someone explain the reason why this happens? thanks

推荐答案

>>> a = [[None] * 2] * 2
>>> id(a[0])
41554168
>>> id(a[1])
41554168
>>> b = [[None, None], [None, None]]
>>> id(b[0])
41549576
>>> id(b[1])
41557368

这应该解释

这篇关于python嵌套列表意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆