Create a 2D array with a nested loop
The following code
n = 3
matrix = [[0] * n] * n
for i in range(n):
for j in range(n):
matrix[i][j] = i * n + j
print(matri开发者_如何学Pythonx)
prints
[[6, 7, 8], [6, 7, 8], [6, 7, 8]]
but what I expect is
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
Why?
Note this:
>>> matrix = [[0] * 3] * 3
>>> [x for x in matrix]
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> [id(x) for x in matrix]
[32484168, 32484168, 32484168]
>>>
Three rows but only one object.
See the docs especially Note 2 about the s * n
operation.
Fix:
>>> m2= [[0] * 3 for i in xrange(5)]
>>> [id(x) for x in m2]
[32498152, 32484808, 32498192, 32499952, 32499872]
>>>
Update: Here are some samples of code that gets an answer simply (i.e. without iter()
):
>>> nrows = 2; ncols = 4
>>> zeroes = [[0 for j in xrange(ncols)] for i in xrange(nrows)]
>>> zeroes
[[0, 0, 0, 0], [0, 0, 0, 0]]
>>> ap = [[ncols * i + j for j in xrange(ncols)] for i in xrange(nrows)]
>>> ap
[[0, 1, 2, 3], [4, 5, 6, 7]]
>>>
Try running matrix[0][0] = 0
after that. Notice it now becomes:
[[0, 7, 8], [0, 7, 8], [0, 7, 8]]
So it's changing all three at the same time.
Read this: http://www.daniweb.com/software-development/python/threads/58916
That seems to explain it.
>>> it = iter(range(9))
>>> [[next(it) for i in range(3)] for i in range(3)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
just replace 3
with n
and 9
with n**2
Also (just answer the "why?"), you're making copies of the same list with multiplication and, therefore, modifying one of them will modify all of them.
精彩评论