尝试修改单个值时,2D 列表有奇怪的行为 [英] 2D list has weird behavor when trying to modify a single value
本文介绍了尝试修改单个值时,2D 列表有奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
Python 列表中的意外功能
所以我对 Python 比较陌生,并且在使用 2D 列表时遇到了问题.
这是我的代码:
data = [[无]*5]*5数据[0][0] = '单元格A1'打印数据
这里是输出(为了可读性而格式化):
[['Cell A1', None, None, None, None],['单元格 A1',无,无,无,无],['单元格 A1',无,无,无,无],['单元格 A1',无,无,无,无],['单元格 A1',无,无,无,无]]
为什么每一行都被赋值?
解决方案
这将创建一个包含五个对相同列表的引用的列表:
data = [[无]*5]*5
使用类似这样的东西来创建五个单独的列表:
<预><代码>>>>数据 = [[无]*5 for _ in range(5)]现在它可以满足您的期望:
<预><代码>>>>数据[0][0] = '单元格A1'>>>打印数据[['单元格 A1',无,无,无,无],[无,无,无,无,无],[无,无,无,无,无],[无,无,无,无,无],[无,无,无,无,无]]Possible Duplicate:
Unexpected feature in a Python list of lists
So I am relatively new to Python and I am having trouble working with 2D Lists.
Here's my code:
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]]
这篇关于尝试修改单个值时,2D 列表有奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文