Is it possible to create an n dimensional array? If so, how to implement it? If the matrix is ​​a "list of lists", then it will look something like this:

 [ [ [...[]...] ],[ [...[]...] ] ] 

Well, or to make it clearer, like n nested segments, the picture below,

 (a1[...[]...]b1, a2_m[...[]...]b2_m,...) 

enter image description here

And how to implement it in the code? If we say, I need to enter n from the keyboard. Thank you very much!

Here's a question about multidimensional arrays that didn't fit me.

    2 answers 2

    I tried to use recursion. The first argument is the depth of the array. The second argument is the number of elements in the array.

     def quant_array(n, x): try: assert isinstance(n, int) except AssertionError: return "Input an integer!" if n <= 1: return [n]*x return [(n, quant_array(n-1, x))]*x print(quant_array(3, 2)) 

    [(3, [(2, [1, 1]), (2, [1, 1])]), (3, [(2, [1, 1]), (2, [1, 1]) ])]

    • Thank you, and how to fill it, for example, with zeros? - Awesome Man
    • one
      Updated the code, it might bring an idea. - jumpman24

    To create an n dimensional numpy array, in which each dimension has n elements:

     >>> import numpy as np # $ pip install numpy >>> n = 3 >>> np.arange(n**n).reshape(*[n]*n) array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]) 

    If you want all n elements to be:

     >>> np.arange(n).reshape(n, *[1]*(n-1)) array([[[0]], [[1]], [[2]]]) 
    • why is the asterisk at the beginning: *[n]*n ? reshape([n]*n) - should work too - MaxU
    • @MaxU yes, the first example works with and without an asterisk. In the second star is not optional. I started editing with an example with several arguments (according to the documentation, I do not see any support for this case at all). - jfs
    • here is an alternative: np.arange(n).reshape((n,) + tuple([1]*(n-1))) - MaxU
    • @MaxU [n]+[1]*(n-1) also works. It is possible and so, the main thing is not to mix reshape((n, m)) and reshape (n, m) `(without the extra brackets it is slightly more beautiful, but this is a matter of taste). - jfs