I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:
double dArray[][][] = new double[x.l
If you restrict yourself to the Python standard library, then a list of lists is the closest construct:
arr = [[1,2],[3,4]]
gives a 2d-like array. The rows can be accessed as arr[i]
for i
in {0,..,len(arr}
, but column access is difficult.
If you are willing to add a library dependency, the NumPy package is what you really want. You can create a fixed-length array from a list of lists using:
import numpy
arr = numpy.array([[1,2],[3,4]])
Column access is the same as for the list-of-lists, but column access is easy: arr[:,i]
for i
in {0,..,arr.shape[1]}
(the number of columns).
In fact NumPy arrays can be n-dimensional.
Empty arrays can be created with
numpy.empty(shape)
where shape
is a tuple of size in each dimension; shape=(1,3,2)
gives a 3-d array with size 1 in the first dimension, size 3 in the second dimension and 2 in the 3rd dimension.
If you want to store objects in a NumPy array, you can do that as well:
arr = numpy.empty((1,), dtype=numpy.object)
arr[0] = 'abc'
For more info on the NumPy project, check out the NumPy homepage.