Python – 3D 矩阵到坐标列表
给定一个矩阵,行的每个元素都是列表,将每列配对以形成坐标。
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.
方法 #1:使用循环 + zip()
在此,我们迭代内部元组列表中的所有配对元素,该列表使用 zip() 配对,并附加结果列表。
Python3
# Python3 code to demonstrate working of
# 3D Matrix to Coordinate List
# Using loop + zip()
# initializing list
test_list = [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]]
# printing original list
print("The original list is : " + str(test_list))
res = []
for sub1, sub2 in test_list:
# zip() used to form pairing
for ele in zip(sub1, sub2):
res.append(ele)
# printing result
print("Constructed Pairs : " + str(res))
Python3
# Python3 code to demonstrate working of
# 3D Matrix to Coordinate List
# Using loop + zip()
# initializing list
test_list = [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]]
# printing original list
print("The original list is : " + str(test_list))
# list comprehension to perform task in shorthand
res = [ele for sub1, sub2 in test_list for ele in zip(sub1, sub2)]
# printing result
print("Constructed Pairs : " + str(res))
输出
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)]
方法#2:使用列表推导
在此,我们使用列表推导以速记方式执行上述方法的任务。
Python3
# Python3 code to demonstrate working of
# 3D Matrix to Coordinate List
# Using loop + zip()
# initializing list
test_list = [[[5, 6, 7], [2, 4, 6]], [[9, 2], [10, 3]], [[13, 6], [19, 7]]]
# printing original list
print("The original list is : " + str(test_list))
# list comprehension to perform task in shorthand
res = [ele for sub1, sub2 in test_list for ele in zip(sub1, sub2)]
# printing result
print("Constructed Pairs : " + str(res))
输出
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)]