Given a (N + 1) * N Matrix, assign each column of 1st row of matrix, the subsequent row of Matrix.
Input : test_list = [[5, 8, 10], [2, 0, 9], [5, 4, 2], [2, 3, 9]] Output : {5: [2, 0, 9], 8: [5, 4, 2], 10: [2, 3, 9]}
Explanation : 5 paired with 2nd row, 8 with 3rd and 10 with 4th
Input : test_list = [[5, 8], [2, 0], [5, 4]] Output : {5: [2, 0], 8: [5, 4]}
Explanation : 5 paired with 2nd row, 8 with 3rd.
Method #1: Using dictionary comprehension
This is one of the ways in which this task can be performed. In this, we iterate for rows and corresponding columns using loop and assign value list accordingly in a one-liner way using dictionary comprehension.
Python3
test_list = [[ 5 , 8 , 9 ], [ 2 , 0 , 9 ], [ 5 , 4 , 2 ], [ 2 , 3 , 9 ]]
print ( "The original list : " + str (test_list))
res = {test_list[ 0 ][ele] : test_list[ele + 1 ] for ele in range ( len (test_list) - 1 )}
print ( "The Assigned Matrix : " + str (res))
|
OutputThe original list : [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
The Assigned Matrix : {5: [2, 0, 9], 8: [5, 4, 2], 9: [2, 3, 9]}
Time complexity: O(m*n), because it performs the same number of iterations as the original code.
Auxiliary space: O(m*n) as well, because it creates a dictionary with m * n keys and a list of m * n elements
Method #2 : Using zip() + list slicing + dict()
This is yet another way in which this task can be performed. In this, we slice elements to be first row and subsequent rows using list slicing and zip() performs the task of required grouping. Returned
Python3
test_list = [[ 5 , 8 , 9 ], [ 2 , 0 , 9 ], [ 5 , 4 , 2 ], [ 2 , 3 , 9 ]]
print ( "The original list : " + str (test_list))
res = dict ( zip (test_list[ 0 ], test_list[ 1 :]))
print ( "The Assigned Matrix : " + str (res))
|
OutputThe original list : [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
The Assigned Matrix : {5: [2, 0, 9], 8: [5, 4, 2], 9: [2, 3, 9]}
Method #3 : Using for loop and slicing
Python3
test_list = [[ 5 , 8 , 9 ], [ 2 , 0 , 9 ], [ 5 , 4 , 2 ], [ 2 , 3 , 9 ]]
print ( "The original list : " + str (test_list))
a = test_list[ 0 ]
b = test_list[ 1 : len (test_list)]
d = dict ()
for i in range ( 0 , len (a)):
d[a[i]] = b[i]
print ( "The Assigned Matrix : " + str (d))
|
OutputThe original list : [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
The Assigned Matrix : {5: [2, 0, 9], 8: [5, 4, 2], 9: [2, 3, 9]}