I'm fairly new to python so I'm sorry if this is a fairly noob question. But I'm writing a 2D list composed of data from .txt file with a for loop (all that code works), but the loop seems to be overwriting all my previously written data each time to passes though even though I'm
This isn't my actually code, but sum up the problem I'm having.
stuff = [[None]*3]*10
for index in range(10):
stuff[index][2]=index
print(stuff)
[[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9],[None, None, 9]]
Why are all the values being returned as 9, why what do I have to do to get it to return as
[[None, None, 1],[None, None, 2],[None, None, 3],[None, None, 4],[None, None, 5],[None, None, 6],[None, None, 7],[None, None, 8],[None, None, 9]]
解决方案
The reason that this is happening is because of your first line:
stuff = [[None]*3]*10
What this is actually doing is creating only 1 array of [[None]*3] and then referencing it 10 times.
So your array is actually similar to:
[[[None]*3], reference 0, reference 0, reference 0, reference 0, reference 0, reference 0, reference 0, reference 0, reference 0]
Change your first line to:
stuff = [[None]*3 for i in xrange(10)]
Which will create a unique element at each position within the array.
本文探讨了使用Python创建二维列表时出现的数据覆盖问题,并提供了解决方案。问题源于列表元素的重复引用,导致每次循环更新时都修改了相同的内存地址。通过使用列表推导式创建独立的子列表来避免这一问题。
2520

被折叠的 条评论
为什么被折叠?



