尝试修改单个值时,二维列表具有怪异的行为
发布于 2021-01-29 19:36:50
因此,我对Python还是比较陌生,在使用2D列表时遇到了麻烦。
这是我的代码:
data = [[None]*5]*5
data[0][0] = 'Cell A1'
print 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]]
为什么为每一行分配值?
关注者
0
被浏览
86
1 个回答
-
这将形成一个列表,其中包含对 同一 列表的五个引用:
data = [[None]*5]*5
使用类似这样的东西,它将创建五个单独的列表:
>>> data = [[None]*5 for _ in range(5)]
现在,它可以满足您的期望:
>>> data[0][0] = 'Cell A1' >>> print data [['Cell A1', None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]]