Python Multidimensional Arrays

Possible duplicate:
How to initialize a two-dimensional array in Python?

When solving a simple two-dimensional array problem, I found a solution on this site that explained how to declare it in Python using the overload operator.

Example:

Myarray = [[0]*3]*3 

this will create the following array (list)

 [[0,0,0],[0,0,0],[0,0,0]] 

This seems great until you use it:

if you assign an element, for example:

 Myarray [0][0] = 1 

you will get unexpected output:

 [[1,0, 0],[1,0,0] , [1,0,0]] 

Actually assigning Myarray [1] [0] and Myarray [2] [0] at the same time

My decision:

 Myarray = [[][][]] for i in range(0,3): for j in range (0,3): Myarray[i].append(0) 

This solution works as intended:

 Marray[0][1] = 1 

gives you

 [[1,0, 0],[0,0,0] , [0,0,0]] 

Is there an easier way ? This was a solution to the Cambridge level A question, and seems too long for students compared to other languages.

+4
source share
1 answer

With vanilla Python you can use this, nested list comprehension

 >>> m = [[0 for y in range(3)] for x in range(3)] >>> m [[0, 0, 0], [0, 0, 0], [0, 0, 0]] 

Unlike the multiplied list you specified in your example, it has the desired behavior

 >>> m[1][0] = 99 >>> m [[0, 0, 0], [99, 0, 0], [0, 0, 0]] 

However, for the serious use of multidimensional arrays and / or numerical programming, I would suggest using Numpy arrays.

+6
source

Source: https://habr.com/ru/post/1444966/


All Articles