Consider the following example:
>>> A = [[]]*3
>>> A
[[], [], []]
>>> for i in range(3):
... for j in range(3):
... A[i].append(i+j)
...
>>> A
[[0, 1, 2, 1, 2, 3, 2, 3, 4], [0, 1, 2, 1, 2, 3, 2, 3, 4], [0, 1, 2, 1, 2, 3, 2, 3, 4]]
But what I really want is something like
A = [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
My guess is that the creation approach doesn't create a list which contains three independent rows, but just create three rows which actually point to the same address or something like that.
The solution (perhaps not the best one) is to create the rows in the form of list comprehension:
>>> A = [[] for rows in range(3)]
>>> A
[[], [], []]
>>> for i in range(3):
... for j in range(3):
... A[i].append(i+j)
...
>>> A
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
No comments:
Post a Comment