How to write a function that generate a multidimensional array based on input data.

например входит число N, то результатом будет массив N на N 
  • one
    Maybe you are satisfied with this option? def getArray (n): res = [] for i in xrange (n): res + = [[0] * n] return res print arrays in language. There is a list, tuple, dictionary. - ReinRaus
  • one
    Well, there is no multidimensional arrays, and there is a transposition of the matrix in seven bytes from Norvig. norvig.com/python-iaq.html - alexlz
  • And you can also make a dict tuple 's length 2. - eigenein

1 answer 1

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.

  • 2
    Have you forgotten about numpy.ndarray? - skegg
  • @mikillskegg, so numpy.zeros is what it is. Arrays should be constructed using array , zeros or empty . - drdaeman
  • one
    And if you need an array of not numeric data, but something else? zero - only a very private convenience. And so the questioner needs to point to the main container, and not to the special case. - skegg
  • one
    I agree, a fair comment. Edited, added. - drdaeman