简体   繁体   中英

Initializing a N x M matrix in python

I'm trying to learn python. In it, I'm trying to dynamically generate a N x M matrix in python, where each cell contains the index value of that cell in python.

The matrix would look like:
[0,1,2,3,4
 0,1,2,3,4
 ...]

I know that in java it would go something like:

a={}{}

    for (i=0;i<N;i++)
      for (j=0;j<M:j++)
         a[i][j] = i

Where N is the width of the matrix and M is the height of the matrix

Except in python it seems like I can't iterate on a matrix on the basis of the cell placement, rather I need to iterate on the basis of the elements in the cell. From my experience something like

a = [][]
a = np.zeroes((N, M))
[ 0, 0, 0
  0, 0, 0]

in the case where N = 3, and M = 2

and then the same style of a loop:

j = 0
   for i in len(a):
     a[i][j] = i
       if i == len(a):
           j = j+1

doesn't work because python can't iterate on the basis of the places of the elements. Perhaps I am wrong. Would this work? Is there a better way to make such a matrix and fill it with the indexed values?

Since you're already using NumPy, you could use numpy.arange and numpy.tile :

In [26]: N = 5

In [27]: M = 4

In [28]: np.tile(np.arange(N), (M, 1))
Out[28]: 
array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])

Another option is to create a row using np.arange(5) and assign it to every row of zeros matrix.

In [22]: m = np.zeros((4,5))

In [23]: m[:,] = np.arange(5)

In [24]: m
Out[24]: 
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 0.,  1.,  2.,  3.,  4.],
       [ 0.,  1.,  2.,  3.,  4.],
       [ 0.,  1.,  2.,  3.,  4.]])

Some example similar to your Java example, but with python syntax sugar.

>>> N=M=5
>>> for z in [[n for n in xrange(N)] for m in xrange(M)]:
...     print z
... 
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]

Here is the code in which matrix contain index value of that cell:

n,m=map(int,raw_input().split())
a=n*[m*[0]]
j=0
for i in range (0,n):
    for j in range(0,m):
        a[i][j]=j
for i in range (0,n):
    for j in range(0,m):
        print a[i][j],
    print

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM