Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create 3D array using Python

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

like image 926
Laís Minchillo Avatar asked May 19 '12 19:05

Laís Minchillo


People also ask

How do you create a 3-dimensional array using numpy in Python?

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.]]])

How do you create a multidimensional array in Python?

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.


2 Answers

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]]] 
like image 116
robert Avatar answered Oct 08 '22 00:10

robert


numpy.arrays 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.

like image 21
mata Avatar answered Oct 07 '22 22:10

mata