📜  Intersection()函数Python(1)

📅  最后修改于: 2023-12-03 15:31:25.640000             🧑  作者: Mango

Python中的Intersection()函数

在Python中,Intersection()函数用于获得两个或多个集合中都存在的元素,并返回一个集合:

set1 = {2, 4, 6, 8}
set2 = {4, 8, 12}
intersection = set1.intersection(set2)
print(intersection) # {8, 4}

上述代码中,我们使用Intersection()函数获取了两个集合set1和set2中都存在的元素(4和8),并将它们存储在一个新的集合中intersection中。我们最终使用了print语句输出了这个新的集合。

除了使用Intersection()函数之外,我们还可以使用运算符“&”来创建一个新的集合,其中包含两个集合中都存在的元素:

set1 = {2, 4, 6, 8}
set2 = {4, 8, 12}
intersection = set1 & set2
print(intersection) # {8, 4}

需要注意的是,Intersection()函数和运算符“&”都只适用于集合类型,所以必须先将列表、元组等其他类型的数据转换为集合。例如:

list1 = [2, 4, 6, 8]
list2 = [4, 8, 12]
set1 = set(list1) # 将list1转换为集合
set2 = set(list2) # 将list2转换为集合
intersection = set1.intersection(set2)
print(intersection) # {8, 4}

在上面的例子中,我们首先创建了两个列表list1和list2,然后将它们分别转换为集合类型set1和set2。由于Intersection()函数只适用于集合类型,我们必须先将这两个列表转换为集合。最终,我们使用Intersection()函数找到了set1和set2中都存在的元素。