I am trying to access a particular element of a list of lists in Python. I am bringing a bit of C/Java baggage and thinking of this data structure as a 2D array. In my mind, the operation below should affect the first item of the first list only, loc1[0][0] in Java speak. In practice, the first item of each sublist is affected, i.e. loc1[0][0], loc1[1][0] and loc1[2][0]. Any idea why that is?
def move(loc, dir, nrows, ncols):
loc1 = [[0.0] * ncols] * nrows
for col in range(1):
for row in range(1):
loc1[row][col] += 100.0 * loc[row][col]
return loc1
nrows = 4
ncols = 3
p = [[1.0 / (ncols * nrows)] * ncols] * nrows #uniform prior
print p
p = move(p, [0, 1], nrows, ncols)
print p
解决方案
I've had this happen before and it's frustrating.
Your problem is this line of code, which isn't doing what you think it is:
loc1 = [[0.0] * ncols] * nrows
[0.0] * ncols creates a single list which is passed by reference to form your 2D list.
Try this:
loc1 = [[0.0 for y in range(ncols)] for x in range(nrows)]