Python list writing through loop, all previous val

2020-05-06 11:28发布

问题:

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]]

回答1:

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.



回答2:

You are putting the same exact array in the list ten times. Updating one of the arrays is updating all of them. Try:

stuff = [[None]*3 for i in xrange(10)]