Python List Of Lists- Access To Individual Elements
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 op
Solution 1:
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.0for y in range(ncols)] for x in range(nrows)]
Solution 2:
[x]*n
produces a list that contains the exact same x
element n
times.
L = [0.0] * ncols
works because 0.0
is a float and floats are immutable in Python therefore L[0] += 1.1
doesn't change 0.0
but places 1.1
in its place.
Lists are mutable therefore when you change any row in L = [[0]*ncol]*nrow
you change all of them because it is the same object.
To fix it you could:
L = [[0.0]*ncols for _ in xrange(nrows)]
It creates a new list for each row so you can change them independently.
Or:
from itertools importrepeatL= [[0.0]*ncols for _ in repeat(None, nrows)]
Whatever is more readable for you.
Post a Comment for "Python List Of Lists- Access To Individual Elements"