Python3 集合 intersection() 方法

2023-02-28 09:53 更新

Python3 列表 Python 集合

描述

intersection() 方法用于返回兩個或更多集合中都包含的元素,即交集。

語法

intersection() 方法語法:

set.intersection(set1, set2 ... etc)

參數(shù)

  • set1 -- 必需,要查找相同元素的集合
  • set2 -- 可選,其他要查找相同元素的集合,可以多個,多個使用逗號 , 隔開

返回值

返回一個新的集合。

實例

返回一個新集合,該集合的元素既包含在集合 x 又包含在集合 y 中:

實例 1

x = {"apple", "banana", "cherry"}
y = {"google", "w3cschool", "apple"}
 
z = x.intersection(y) 
 
print(z)

輸出結(jié)果為:

{'apple'}

計算多個集合的交集:

實例 3

x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
 
result = x.intersection(y, z)
 
print(result)

輸出結(jié)果為:

{'c'}

Python3 列表 Python 集合


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號