m,n=input()
a=[0]*n
for i in range(0,m):
a[i]=[0]*m
for i in range(0,m):
for j in range(0,n):
a[i][j]=input()
print a
Consider the above piece of code written in Python 2.7.4 to accept a 2-D array and then print it. This code functions well but it should accept any 2-D array means for example the values of m and could be 3,2 respectively let's say but it only accepts a square matrix. We cannot create a rectangular matrix because it gives the error: index out of range if the values of m and n are not equal. Is there any way to create a rectangular matrix just like we can do in C/C++ easily?
You can do something like this:
rows = input()
cols = input()
arr = [[None] * cols for _ in range(rows)]
for i in range(rows):
for j in range(cols):
print(arr)
arr[i][j] = input()
print(arr)
You should see this similar question: How to initialize a two-dimensional array in Python?
As far as getting your exact code to work, you just have m
and n
switched on lines 2 & 4:
m = input() # rows
n = input() # cols
a = [0] * m # Initialize rows
for i in range(0, m): # For each row (must be n rows)
a[i] = [0] * n # Initialize a column
for i in range(0, m): # For each row
for j in range(0, n): # For each column
a[i][j] = input() # Input a value
print a
Numpy is a great module for fast linear algebra operations. You can create a rectangular array with Numpy which is essentially a matrix. (Numpy also has matrix functions too but they are a little more tedious to work with).
As an example, create a 3x4 array as follows
import numpy as np
input = np.zeros((3, 4)) #This creates a 3x4 array. It is good practice to initialize your array with 0's
input[0][3] = 5 #Fill out your array. The 0,0 index is the top left corner
In [42]:input
Out[42]:
array([[ 0., 0., 0., 5.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
Proceed to fill out the rest of your rectangular matrix as per normal.
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.