Python – 分组相邻坐标
有时,在使用Python列表时,我们可能会遇到一个问题,即我们需要对矩阵上相邻的所有坐标进行分组,即水平和垂直距离为 1。这称为曼哈顿距离。这类问题可能发生在竞争性编程领域。让我们讨论一下可以执行此任务的特定方式。
Input : test_list = [(4, 4), (6, 4), (7, 8)]
Output : [[(7, 8)], [(6, 4)], [(4, 4)]]
Input : test_list = [(4, 4), (5, 4)]
Output : [[(5, 4), (4, 4)]]
方法:使用 product() + groupby() + list comprehension
上述方法的组合可以用来解决这个问题。在此,我们使用 groupby() 执行对元素进行分组的任务,并使用 product() 检查对。驱动此解决方案的逻辑类似于联合查找算法。
Python3
# Python3 code to demonstrate working of
# Group Adjacent Coordinates
# Using product() + groupby() + list comprehension
from itertools import groupby, product
def Manhattan(tup1, tup2):
return abs(tup1[0] - tup2[0]) + abs(tup1[1] - tup2[1])
# initializing list
test_list = [(4, 4), (6, 4), (7, 8), (11, 11),
(7, 7), (11, 12), (5, 4)]
# printing original list
print("The original list is : " + str(test_list))
# Group Adjacent Coordinates
# Using product() + groupby() + list comprehension
man_tups = [sorted(sub) for sub in product(test_list, repeat = 2)
if Manhattan(*sub) == 1]
res_dict = {ele: {ele} for ele in test_list}
for tup1, tup2 in man_tups:
res_dict[tup1] |= res_dict[tup2]
res_dict[tup2] = res_dict[tup1]
res = [[*next(val)] for key, val in groupby(
sorted(res_dict.values(), key = id), id)]
# printing result
print("The grouped elements : " + str(res))
输出
The original list is : [(4, 4), (6, 4), (7, 8), (11, 11), (7, 7), (11, 12), (5, 4)]
The grouped elements : [[(6, 4), (5, 4), (4, 4)], [(7, 8), (7, 7)], [(11, 12), (11, 11)]]