Python – 3D Matrix to Coordinate List
Last Updated :
03 May, 2023
Given a Matrix, row’s each element is list, pair each column to form coordinates.
Input : test_list = [[[9, 2], [10, 3]], [[13, 6], [19, 7]]] Output : [(9, 10), (2, 3), (13, 19), (6, 7)] Explanation : Column Mapped Pairs. Input : test_list = [[[13, 6], [19, 7]]] Output : [(13, 19), (6, 7)] Explanation : Column Mapped Pairs.
Method #1 : Using loop + zip()
In this, we iterate for all the paired elements in inner tuples list, which is paired using zip(), and append the result list.
Python3
test_list = [[[ 5 , 6 , 7 ], [ 2 , 4 , 6 ]], [[ 9 , 2 ], [ 10 , 3 ]], [[ 13 , 6 ], [ 19 , 7 ]]]
print ( "The original list is : " + str (test_list))
res = []
for sub1, sub2 in test_list:
for ele in zip (sub1, sub2):
res.append(ele)
print ( "Constructed Pairs : " + str (res))
|
Output
The original list is : [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]]
Constructed Pairs : [(5, 2), (6, 4), (7, 6), (9, 10), (2, 3), (13, 19), (6, 7)]
Time Complexity: O(n^2), where n is the total number of elements in the 3D matrix.
Auxiliary Space: O(n)
Method #2 : Using list comprehension
In this, we perform task of of above method in shorthand using list comprehension.
Python3
test_list = [[[ 5 , 6 , 7 ], [ 2 , 4 , 6 ]], [[ 9 , 2 ], [ 10 , 3 ]], [[ 13 , 6 ], [ 19 , 7 ]]]
print ( "The original list is : " + str (test_list))
res = [ele for sub1, sub2 in test_list for ele in zip (sub1, sub2)]
print ( "Constructed Pairs : " + str (res))
|
Output
The original list is : [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]]
Constructed Pairs : [(5, 2), (6, 4), (7, 6), (9, 10), (2, 3), (13, 19), (6, 7)]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...