How to input matrix (2D list) in Python 3.4?

2019-02-09 07:55发布

I am new to Python 3.4 and I usually use MATLAB/ GNU Octave for matrix calculation. I know we can perform matrix calculation using numpy in Python 2.x, but numpy does not work for Python 3.4.

I tried to create this code to input an m by n matrix. I intended to input [[1,2,3],[4,5,6]] but the code yields [[4,5,6],[4,5,6]. Same things happen when I input other m by n matrix, the code yields an m by n matrix whose rows are identical.

Perhaps you can help me to find what is wrong with my code.

m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []; columns = []
# initialize the number of rows
for i in range(0,m):
  matrix += [0]
# initialize the number of columns
for j in range (0,n):
  columns += [0]
# initialize the matrix
for i in range (0,m):
  matrix[i] = columns
for i in range (0,m):
  for j in range (0,n):
    print ('entry in row: ',i+1,' column: ',j+1)
    matrix[i][j] = int(input())
print (matrix)

10条回答
Luminary・发光体
2楼-- · 2019-02-09 08:11

This code takes number of row and column from user then takes elements and displays as a matrix.

m = int(input('number of rows, m : '))
n = int(input('number of columns, n : '))
a=[]
for i in range(1,m+1):
  b = []
  print("{0} Row".format(i))
  for j in range(1,n+1):
    b.append(int(input("{0} Column: " .format(j))))
  a.append(b)
print(a)
查看更多
ら.Afraid
3楼-- · 2019-02-09 08:16
row=list(map(int,input().split())) #input no. of row and column
b=[]
for i in range(0,row[0]):
    a=list(map(int,input().split()))
    b.append(a)
print(b)

input

2 3
1 2 3
4 5 6

output [[1, 2, 3], [4, 5, 6]]

查看更多
你好瞎i
4楼-- · 2019-02-09 08:17
row=list(map(int,input().split())) #input no. of row and column
b=[]
for i in range(0,row[0]):
    print('value of i: ',i)
    a=list(map(int,input().split()))
    print(a)
    b.append(a)
print(b)
print(row)

Output:

2 3

value of i:0
1 2 4 5
[1, 2, 4, 5]
value of i:  1
2 4 5 6
[2, 4, 5, 6]
[[1, 2, 4, 5], [2, 4, 5, 6]]
[2, 3]

Note: this code in case of control.it only control no. Of rows but we can enter any number of column we want i.e row[0]=2 so be careful. This is not the code where you can control no of columns.

查看更多
混吃等死
5楼-- · 2019-02-09 08:21

If your matrix is given in row manner like below, where size is s*s here s=5 5 31 100 65 12 18 10 13 47 157 6 100 113 174 11 33 88 124 41 20 140 99 32 111 41 20

then you can use this

s=int(input())
b=list(map(int,input().split()))
arr=[[b[j+s*i] for j in range(s)]for i in range(s)]

your matrix will be 'arr'

查看更多
登录 后发表回答