Python|价值清单联盟
union 的功能已经讨论过很多次了。但有时,我们可以有一个更复杂的容器,我们需要在其中检查以字典键形式存在的列表的并集。让我们讨论解决此类问题的某些方法。
方法#1:使用循环
使用循环是执行此特定任务的一种天真的蛮力方法。在这种方法中,我们检查列表中存在的键并检查非重复值以添加到结果中。我们甚至检查其他完全不存在的键以添加其整个列表值。
# Python3 code to demonstrate
# Union of Value Lists
# using loops
# initializing dicts
test_dict1 = { "Key1" : [1, 3, 4], "key2" : [4, 5] }
test_dict2 = { "Key1" : [1, 7, 8] }
# printing original dicts
print("The original dict 1 : " + str(test_dict1))
print("The original dict 2 : " + str(test_dict2))
# using loops
# Union of Value Lists
for key in test_dict1:
if key in test_dict2:
for val in test_dict1[key]:
if val not in test_dict2[key]:
test_dict2[key].append(val)
else:
test_dict2[key] = test_dict1[key][:]
# print result
print("The dicts after union is : " + str(test_dict2))
输出 :
The original dict 1 : {'Key1': [1, 3, 4], 'key2': [4, 5]}
The original dict 2 : {'Key1': [1, 7, 8]}
The dicts after union is : {'Key1': [1, 7, 8, 3, 4], 'key2': [4, 5]}
方法#2:使用字典理解+集合操作
这是解决类似问题的单线方法,并为上述方法提供了一种紧凑的替代方案。此解决方案通过使用集合推导来处理,以使用字典推导将必要的元素绑定到列表中。
# Python3 code to demonstrate
# Union of Value Lists
# using dictionary comprehension + set operations
# initializing dicts
test_dict1 = { "Key1" : [1, 3, 4], "key2" : [4, 5] }
test_dict2 = { "Key1" : [1, 7, 8] }
# printing original dicts
print("The original dict 1 : " + str(test_dict1))
print("The original dict 2 : " + str(test_dict2))
# using dictionary comprehension + set operations
# Union of Value Lists
res = {key : list(set(test_dict1.get(key, []) + test_dict2.get(key, [])))
for key in set(test_dict2) | set(test_dict1)}
# print result
print("The dicts after union is : " + str(res))
输出 :
The original dict 1 : {'Key1': [1, 3, 4], 'key2': [4, 5]}
The original dict 2 : {'Key1': [1, 7, 8]}
The dicts after union is : {'Key1': [1, 7, 8, 3, 4], 'key2': [4, 5]}