I would like to create a 3D array in Python (2.7) to use like this:
distance[i][j][k]
And the sizes of the array should be the size of a variable I have. (nnn)
I tried using:
distance = [[[]*n]*n]
but that didn't seem to work.
I can only use the default libraries, and the method of multiplying (i.e.,[[0]*n]*n
) wont work because they are linked to the same pointer and I need all of the values to be individual
Let's look at a full example: >>> a = np. zeros((2, 3, 4)) >>> a array([[[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]], [[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]]])
In Python, Multidimensional Array can be implemented by fitting in a list function inside another list function, which is basically a nesting operation for the list function. Here, a list can have a number of values of any data type that are segregated by a delimiter like a comma.
You should use a list comprehension:
>>> import pprint >>> n = 3 >>> distance = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(n)] >>> pprint.pprint(distance) [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]] >>> distance[0][1] [0, 0, 0] >>> distance[0][1][2] 0
You could have produced a data structure with a statement that looked like the one you tried, but it would have had side effects since the inner lists are copy-by-reference:
>>> distance=[[[0]*n]*n]*n >>> pprint.pprint(distance) [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]] >>> distance[0][0][0] = 1 >>> pprint.pprint(distance) [[[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]]]
numpy.array
s are designed just for this case:
numpy.zeros((i,j,k))
will give you an array of dimensions ijk, filled with zeroes.
depending what you need it for, numpy may be the right library for your needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With