欢迎各位兄弟 发布技术文章
这里的技术是共享的
在 Python 中,可以通过多种方式获取两个列表的并集。并集指的是两个列表中所有独特的元素,且每个元素只出现一次。以下是几种常用的方法来实现这一点:
将列表转换为 set 可以自动去重,然后通过使用 union() 或 | 操作符获取并集。
pythonlist1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6] # 使用 set() union_set = set(list1) | set(list2) print("并集:", list(union_set))
pythonlist1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6] # 使用 set.union() union_set = set(list1).union(set(list2)) print("并集:", list(union_set))
如果你想保留列表的顺序并去重,可以使用列表推导式结合 in 来实现。
pythonlist1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6] # 使用列表推导式保留顺序 union_list = list1 + [item for item in list2 if item not in list1] print("并集:", union_list)
在 Python 3.7 之前,普通的 set 是无序的,所以如果你需要保留插入顺序,可以使用 OrderedDict。
pythonfrom collections import OrderedDict list1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6] # 使用 OrderedDict 保留顺序 union_list = list(OrderedDict.fromkeys(list1 + list2)) print("并集:", union_list)
如果你使用 numpy,可以利用其提供的函数来得到并集,并且可以选择是否保留顺序:
pythonimport numpy as np list1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6] # 使用 numpy union_array = np.union1d(list1, list2) print("并集:", union_array)
以下是一个完整的示例,展示了所有这些方法:
pythonlist1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6] # 方法 1: 使用 set() union_set = set(list1) | set(list2) print("方法 1 - 并集:", list(union_set)) # 方法 2: 使用 set.union() union_set = set(list1).union(set(list2)) print("方法 2 - 并集:", list(union_set)) # 方法 3: 使用列表推导 union_list = list1 + [item for item in list2 if item not in list1] print("方法 3 - 并集:", union_list) # 方法 4: 使用 OrderedDict from collections import OrderedDict union_list = list(OrderedDict.fromkeys(list1 + list2)) print("方法 4 - 并集:", union_list) # 方法 5: 使用 numpy import numpy as np union_array = np.union1d(list1, list2) print("方法 5 - 并集:", union_array)
方法 1 - 并集: [1, 2, 3, 4, 5, 6]
方法 2 - 并集: [1, 2, 3, 4, 5, 6]
方法 3 - 并集: [1, 2, 3, 4, 5, 6]
方法 4 - 并集: [1, 2, 3, 4, 5, 6]
方法 5 - 并集: [1. 2. 3. 4. 5. 6.]
这些方法可根据你需要的特性(是否保留顺序、是否使用外部库等)来选择。