尝试修改单个值时,二维列表具有怪异的行为 [英] 2D list has weird behavor when trying to modify a single value
本文介绍了尝试修改单个值时,二维列表具有怪异的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
Python列表列表中的意外功能
Possible Duplicate:
Unexpected feature in a Python list of lists
所以我对Python还是比较陌生,在处理2D列表时遇到了麻烦.
So I am relatively new to Python and I am having trouble working with 2D Lists.
这是我的代码:
data = [[None]*5]*5
data[0][0] = 'Cell A1'
print data
这是输出(为便于阅读而设置):
and here is the output (formatted for readability):
[['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 every row get assigned the value?
推荐答案
这将创建一个包含对相同列表的五个引用的列表:
This makes a list with five references to the same list:
data = [[None]*5]*5
使用类似这样的方法创建五个单独的列表:
Use something like this instead which creates five separate lists:
>>> data = [[None]*5 for _ in range(5)]
现在它可以满足您的期望:
Now it does what you expect:
>>> 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]]
这篇关于尝试修改单个值时,二维列表具有怪异的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文