以下是一个示例代码,可以比较两个嵌套列表,并保留元素的并集:
def nested_list_union(list1, list2):
# 将两个嵌套列表合并成一个列表
merged_list = list1 + list2
# 创建一个集合用于存储元素的并集
union_set = set()
# 遍历合并后的列表
for sublist in merged_list:
# 将子列表中的元素添加到集合中
for element in sublist:
union_set.add(element)
# 将集合转换回列表并返回
union_list = list(union_set)
return union_list
# 示例使用
list1 = [[1, 2, 3], [4, 5, 6]]
list2 = [[3, 4, 5], [6, 7, 8]]
result = nested_list_union(list1, list2)
print(result)
输出结果为:
[1, 2, 3, 4, 5, 6, 7, 8]
此代码将两个嵌套列表合并成一个列表,并使用集合来存储元素的并集。然后,将集合转换回列表并返回结果。