Python中的动态矩阵输入

时间:2017-06-19 14:14:34

标签: python matrix dynamic

raw = input("Enret Number of Raws : ")
cols = input("Enter Number of Cols : ")

obj = []
mat = [[[] for j in range(raw)] for i in range(cols)]
for k in range(2):
    for i in range(cols):
        for j in range(raw):
            number = int(input("Please Enter Elements of Matrix : "))
            mat[i][j] = number
    obj.append(mat)
    print obj

输出:

Enret Number of Raws : 2
Enter Number of Cols : 2
Please Enter Elements of Matrix 1:9
Please Enter Elements of Matrix 1:3
Please Enter Elements of Matrix 1:7
Please Enter Elements of Matrix 1:1
[[[9, 3], [7, 1]]]
Please Enter Elements of Matrix 2:8
Please Enter Elements of Matrix 2:2
Please Enter Elements of Matrix 2:4
Please Enter Elements of Matrix 2:6
[[[8, 2], [4, 6]], [[8, 2], [4, 6]]]

在列表中追加第二个矩阵后,第1个值会更改。

2 个答案:

答案 0 :(得分:1)

raw = input("Enret Number of Raws : ")
cols = input("Enter Number of Cols : ")

obj = []

for k in range(2):
    mat = [[[] for j in range(raw)] for i in range(cols)]


    for i in range(cols):
        for j in range(raw):
            number = int(input("Please Enter Elements of Matrix : "))
            mat[i][j] = number
    obj.append(mat)
    print obj

答案 1 :(得分:0)

raw = int(input("Enret Number of Raws : "))

cols = int(input("Enter Number of Cols : "))

mat=[]

for i in range(raw):

   a=[]

   for j in range(cols):

      j=int(input("Enter Number in pocket ["+str(i)+"]["+str(j)+"]"))

      a.append(j)

   mat.append(a)

print(mat)