在python 3.x 版本中 set 中有函數intersection()
intersection() 方法用於返回兩個或更多集合中都包含的元素,即交集。
語法:
set.intersection(set1, set2 ... etc)
參數:
- set1 -- 必需,要查找相同元素的集合
- set2 -- 可選,其他要查找相同元素的集合,可以多個,多個使用逗號 , 隔開
返回值:
返回一個新的集合
實操:
a = [5, 6, 7, 8, 9]
b = [4, 6, 7, 8, 10]
print(set(a).intersection(set(b)))
a = {5, 6, 7, 8, 9}
b = {4, 6, 7, 8, 10}
print(a.intersection(b))
輸出結果:
{8, 6, 7}
{8, 6, 7}