Python Set intersection() 方法
描述
intersection() 方法用於返回兩個或更多集合中都包含的元素,即交集。
語法
intersection() 方法語法:
set.intersection(set1, set2 ... etc)
參數
- set1 -- 必需,要查找相同元素的集合
- set2 -- 可選,其他要查找相同元素的集合,可以多個,多個使用逗號 , 隔開
返回值
返回一個新的集合。
實例
返回一個新集合,該集合的元素既包含在集合 x 又包含在集合 y 中:
實例 1
x = {"apple", "banana", "cherry"}
y = {"google", "zaixian", "apple"}
z = x.intersection(y)
print(z)
輸出結果為:
{'apple'}
計算多個集合的交集:
實例 1
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
result = x.intersection(y, z)
print(result)
輸出結果為:
{'c'}