📜  Python集——intersection_update()函数

📅  最后修改于: 2022-05-13 01:54:27.141000             🧑  作者: Mango

Python集——intersection_update()函数

Python intersection_update()函数用于获取所有给定集合中存在的元素。它将删除所有集合中不存在的元素。

句法:

set.intersection_update(set1,set2,set3,...........,set n)

其中,set1、set2 是输入集。它可以采用任意数量的集合。

注意:要执行此函数,我们至少有两组。

示例:使用字符串元素定义两个集合的Python程序。

Python3
# declare set1
set1 = {"java", "python", "c/cpp", "html"}
  
# declare set2
set2 = {"php", "html", "java", "R"}
  
# display sets
print(set1, set2)
  
# perform intersection_update operation 
# on both the sets
set.intersection_update(set1, set2)
  
# display the result set
print(set1)


Python3
# declare set1
set1 = {"java", "python", "c/cpp", "html"}
  
# declare set2
set2 = {"php", "html", "java", "R"}
  
# declare set3
set3 = {"java", "python", "ml", "dl"}
  
# declare set4
set4 = {"python", "java", "swift", "R"}
  
# display sets
print(set1, set2, set3, set4)
  
# perform intersection_update operation on
# all the sets
set.intersection_update(set1, set2, set3, set4)
  
# display the result set
print(set1)


Python3
# declare set1
set1 = {"java", "python", "c/cpp", "html"}
  
# declare set2
set2 = {"php", "cn", "dbms", "R"}
  
# display sets
print(set1, set2)
  
# perform intersection_update operation on 
# both the sets
set.intersection_update(set1, set2)
  
# display the result set
print(set1)


输出:

示例2:对多个集合的 intersection_update 操作。

Python3

# declare set1
set1 = {"java", "python", "c/cpp", "html"}
  
# declare set2
set2 = {"php", "html", "java", "R"}
  
# declare set3
set3 = {"java", "python", "ml", "dl"}
  
# declare set4
set4 = {"python", "java", "swift", "R"}
  
# display sets
print(set1, set2, set3, set4)
  
# perform intersection_update operation on
# all the sets
set.intersection_update(set1, set2, set3, set4)
  
# display the result set
print(set1)

输出:

示例 3:

这里我们创建了两个集合,两个集合中没有共同的元素,所以输出应该是空的。在所有集合中,没有元素是共同的,因此输出是一个空集合。

Python3

# declare set1
set1 = {"java", "python", "c/cpp", "html"}
  
# declare set2
set2 = {"php", "cn", "dbms", "R"}
  
# display sets
print(set1, set2)
  
# perform intersection_update operation on 
# both the sets
set.intersection_update(set1, set2)
  
# display the result set
print(set1)

输出: