How to write a function that generate a multidimensional array based on input data.
например входит число N, то результатом будет массив N на N
How to write a function that generate a multidimensional array based on input data.
например входит число N, то результатом будет массив N на N
If arrays of array.array
or bytearray
, then nothing. Python does not have multidimensional arrays.
Unless to make a one-dimensional array of size n*n
, and to address on an index x+n*y
. For example, like bytearray(n*n)
or, say, array.array("l", [0 for _ in range(0, n*n)])
.
If the concept of a “list of lists” fits the concept of a “multidimensional array” (lists in CPython are implemented exactly as arrays ), then, in fact, make them. For example:
>>> n = 3 >>> [[0 for _ in range(0, n)] for _ in range(0, n)] [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
If matrices are needed, then NumPy can be used:
>>> numpy.matrix(numpy.zeros((n, n))) matrix([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])
Or, if not matrices are needed (and n × n was a special case), then directly, numpy.array
:
>>> numpy.zeros((n, n)) array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])
Or, as @mikillskegg correctly notes, for example, if an array of non-numbers is required, instead of numpy.array
/ numpy.zeros
you can use the lower-level interface numpy.ndarray
:
>>> a = numpy.ndarray(shape=(n, n), dtype=(unicode, 1)) >>> a.fill(u"X") array([[u'X', u'X', u'X'], [u'X', u'X', u'X'], [u'X', u'X', u'X']], dtype='<U1')
In general, the question is strangely formulated, because neither the word is said about the data that should be stored in the structure, nor about the properties that the structure should have.
numpy.zeros
is what it is. Arrays should be constructed using array
, zeros
or empty
. - drdaemanSource: https://ru.stackoverflow.com/questions/158145/
dict
tuple
's length 2. - eigenein