Python – 邻接字典的配对邻居
有时在使用Python对时,我们可能会遇到问题,其中对代表邻居,我们需要计算每个元素的邻居。这种问题在竞争性编程和使用图表时很常见。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可用于解决此问题的方法之一。在此,我们预先假定所需的键并用空列表构造字典,并迭代附加值的对列表。
# Python3 code to demonstrate working of
# Paired Neighbours to Adjacency Dictionary
# Using loop
# initializing list
test_list = [(1, 2), (4, 5), (1, 3), (3, 4), (5, 6), (6, 2)]
# printing original list
print("The original list is : " + str(test_list))
# Paired Neighbours to Adjacency Dictionary
# Using loop
res = {1: [], 2: [], 3: [], 4: [], 5: [], 6: []}
for sub in test_list:
res[sub[0]].append(sub[1])
res[sub[1]].append(sub[0])
# printing result
print("The Neighbours Paired Dictionary : " + str(res))
输出 :
The original list is : [(1, 2), (4, 5), (1, 3), (3, 4), (5, 6), (6, 2)]
The Neighbours Paired Dictionary : {1: [2, 3], 2: [1, 6], 3: [1, 4], 4: [5, 3], 5: [4, 6], 6: [5, 2]}
方法 #2:使用defaultdict()
+ 循环
上述功能的组合也可以用来解决这个问题。在此,我们将字典初始化为默认集。这消除了重复问题,并且还为更多未确定的节点值提供了更大的灵活性。
# Python3 code to demonstrate working of
# Paired Neighbours to Adjacency Dictionary
# Using defaultdict() + loop
from collections import defaultdict
# initializing list
test_list = [(1, 2), (4, 5), (1, 3), (3, 4), (5, 6), (6, 2)]
# printing original list
print("The original list is : " + str(test_list))
# Paired Neighbours to Adjacency Dictionary
# Using defaultdict() + loop
res = defaultdict(set)
for sub in test_list:
res[sub[0]].add(sub[1])
res[sub[1]].add(sub[0])
# printing result
print("The Neighbours Paired Dictionary : " + str(dict(res)))
输出 :
The original list is : [(1, 2), (4, 5), (1, 3), (3, 4), (5, 6), (6, 2)]
The Neighbours Paired Dictionary : {1: {2, 3}, 2: {1, 6}, 3: {1, 4}, 4: {3, 5}, 5: {4, 6}, 6: {2, 5}}