欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

python 得到 列表的并集 AG chatgpt 有大用

在 Python 中,可以通过多种方式获取两个列表的并集。并集指的是两个列表中所有独特的元素,且每个元素只出现一次。以下是几种常用的方法来实现这一点:

1. 使用 set()

将列表转换为 set 可以自动去重,然后通过使用 union() 或 | 操作符获取并集。

python
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]

# 使用 set()
union_set = set(list1) | set(list2)
print("并集:", list(union_set))

2. 使用 set.union()

python
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]

# 使用 set.union()
union_set = set(list1).union(set(list2))
print("并集:", list(union_set))

3. 使用列表推导和 in

如果你想保留列表的顺序并去重,可以使用列表推导式结合 in 来实现。

python
list1 = [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)

4. 使用 collections.OrderedDict 保留顺序

在 Python 3.7 之前,普通的 set 是无序的,所以如果你需要保留插入顺序,可以使用 OrderedDict

python
from collections import OrderedDict

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]

# 使用 OrderedDict 保留顺序
union_list = list(OrderedDict.fromkeys(list1 + list2))
print("并集:", union_list)

5. 使用 numpy(若你在使用数值计算)

如果你使用 numpy,可以利用其提供的函数来得到并集,并且可以选择是否保留顺序:

python
import numpy as np

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]

# 使用 numpy
union_array = np.union1d(list1, list2)
print("并集:", union_array)

例子汇总

以下是一个完整的示例,展示了所有这些方法:

python
list1 = [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.]

这些方法可根据你需要的特性(是否保留顺序、是否使用外部库等)来选择。


普通分类: