Shiv_ka_ansh
Shiv_ka_ansh

Reputation: 57

Separated input matrix from user

Code:

lst = []
for _ in range(int(input())):
    T = int(input())
    for i in range(T):
        matrix = list(map(int, input().split()))
        lst.append(matrix)
    print(lst) 

Input:

3
4
1 2 3 4
2 1 4 3
3 4 1 2
4 3 2 1
4
2 2 2 2
2 3 2 3
2 2 2 3
2 2 2 2
3
2 1 3
1 3 2
1 2 3

On inputting this matrix, the expected output should be [[1, 2, 3, 4], [2, 1, 4, 3], [3, 4, 1, 2], [4, 3, 2, 1]] and so on for other but the matrix is adding with other matrix at last.

I want to retrieve [[2, 1, 3], [1, 3, 2], [1, 2, 3]]. Getting [[1, 2, 3, 4], [2, 1, 4, 3], [3, 4, 1, 2], [4, 3, 2, 1], [2, 2, 2, 2], [2, 3, 2, 3], [2, 2, 2, 3], [2, 2, 2, 2], [2, 1, 3], [1, 3, 2], [1, 2, 3]].

How can I do so??

Upvotes: 1

Views: 56

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114588

You're close. Instead of appending the rows of each matrix to your list, append the rows to a new matrix and then append the matrices to a list. Something like

lst = []
for _ in range(int(input())):  # Loop over number of matrices
    T = int(input())
    matrix = []
    for i in range(T):  # Loop over each row
        row = list(map(int, input().split()))
        matrix.append(row)
    lst.append(matrix)

Now lst[-1] will give you the last 2D matrix in the sequence.

Upvotes: 1

Related Questions