Python – 将矩阵转换为重叠的元组对
有时,在处理Python数据时,我们可能会遇到需要对 Matrix 中的元素进行重叠,并将它们转换为元组对的问题。这类问题可能出现在数据领域的各种应用中。让我们讨论可以执行此任务的某些方式。
Input : test_list = [[5, 6, 3], [8, 6, 2], [2, 5, 1]]
Output : [(5, 6), (6, 3), (8, 6), (6, 2), (2, 5), (5, 1)]
Input : test_list = [[5, 6, 3]]
Output : [(5, 6), (6, 3)]
方法#1:使用循环
这是可以执行此任务的蛮力方式。在此,我们迭代每个列表并提取连续元素并将它们作为对添加到结果列表中。
# Python3 code to demonstrate working of
# Convert Matrix to overlapping Tuple Pairs
# Using loop
# initializing list
test_list = [[5, 6, 7], [8, 6, 5], [2, 5, 7]]
# printing original list
print("The original list is : " + str(test_list))
# Convert Matrix to overlapping Tuple Pairs
# Using loop
res = []
for sub in test_list:
res.append((sub[0], sub[1]))
res.append((sub[1], sub[2]))
# printing result
print("Filtered tuples : " + str(res))
输出 :
The original list is : [[5, 6, 7], [8, 6, 5], [2, 5, 7]]
Filtered tuples : [(5, 6), (6, 7), (8, 6), (6, 5), (2, 5), (5, 7)]
方法#2:使用循环+列表切片
上述功能的组合可以用来解决这个问题。这提供了将逻辑扩展到更多自定义元组大小的灵活性,也超过 2。
# Python3 code to demonstrate working of
# Convert Matrix to overlapping Tuple Pairs
# Using loop + list slicing
# initializing list
test_list = [[5, 6, 7], [8, 6, 5], [2, 5, 7]]
# printing original list
print("The original list is : " + str(test_list))
# Convert Matrix to overlapping Tuple Pairs
# Using loop + list slicing
res = []
for sub in test_list:
for idx in range(len(sub) -1):
res.append(tuple(sub[idx:idx + 2]))
# printing result
print("Filtered tuples : " + str(res))
输出 :
The original list is : [[5, 6, 7], [8, 6, 5], [2, 5, 7]]
Filtered tuples : [(5, 6), (6, 7), (8, 6), (6, 5), (2, 5), (5, 7)]