Python – 检测字典中的循环
有时,在使用Python字典时,我们可能会遇到问题,我们需要检查字典的值在通过其他字典的键映射时是否没有形成循环。这种问题可以在许多领域都有应用,包括竞争性编程和蛮力。
Input : test_dict1 = {9 : [1, 5], 8 : [1, 4], 10 : [4, 2]}
test_dict2 = {2 : [1, 8]}
Output : True
Input : test_dict1 = {15 : [1, 5]}
test_dict2 = {2 : [1, 10]}
Output : False
方法#1:使用循环
这是可以执行此任务的粗暴方式。在此,我们迭代特定字典键的所有值,并映射到字典键中相似键的值。
# Python3 code to demonstrate working of
# Detect loop in Dictionaries
# Using loop
# initializing dictionaries
test_dict1 = {7 : [1, 2], 8 : [1, 4], 9 : [4, 2]}
test_dict2 = {2 : [1, 7], 10 : [1, 6], 11 : [24, 20]}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# Detect loop in Dictionaries
# Using loop
res = False
for idx1 in test_dict1.values():
temp1 = (idx for idx in idx1 if idx in test_dict2)
for idx in temp1:
for idx2 in test_dict2[idx]:
if idx2 in test_dict1:
res = True
# printing result
print("Does dictionaries contain loop : " + str(res))
输出 :
The original dictionary 1 is : {8: [1, 4], 9: [4, 2], 7: [1, 2]}
The original dictionary 2 is : {2: [1, 7], 11: [24, 20], 10: [1, 6]}
Does dictionaries contain loop : True
方法 #2:使用any()
+ 循环
这是解决这个问题的简写。在此,我们通过注入 any() 来减少内部循环,如果存在任何循环,则返回 True。
# Python3 code to demonstrate working of
# Detect loop in Dictionaries
# Using any() + loop
# initializing dictionaries
test_dict1 = {7 : [1, 2], 8 : [1, 4], 9 : [4, 2]}
test_dict2 = {2 : [1, 7], 10 : [1, 6], 11 : [24, 20]}
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# Detect loop in Dictionaries
# Using any() + loop
res = False
for key, val in test_dict1.items():
if any([vl in test_dict2 and key in test_dict2[vl] for vl in val]):
res = True
# printing result
print("Does dictionaries contain loop : " + str(res))
输出 :
The original dictionary 1 is : {8: [1, 4], 9: [4, 2], 7: [1, 2]}
The original dictionary 2 is : {2: [1, 7], 11: [24, 20], 10: [1, 6]}
Does dictionaries contain loop : True