I am trying to create an array. When the number of rows and columns are not same, an empty [] appears at the end.
I also want it to be displayed in correct matrix form of [m x n]
I am new to using Python language and this is my first question.
I hope to find a solution to the problem.
import random
m = int(input("Rows : "))
n = int(input("Columns : "))
Mat = []
for i in range(0,n):
Mat.append([])
for i in range(0,m):
for j in range(0,n):
Mat[i].append(j)
Mat[i][j] = 0
Mat[i][j] = random.randint(1,100)
print(Mat)
Example:
Columns : 2
Rows : 3
Output:
[[7, 49, 61], [47, 2, 40], []]
I need it like this:
[[7, 49, 61],
[47, 2, 40]]
mat = [[random.randint(1, 100) for _ in range(n)] for _ in range(m)]mat, as a numpy array when you print it out. unless you are usingpprint.pprint(mat)or similar to print outmat.Mat[i].append(random.randint(1,100))but the list comprehension above is much better