在Python中,要對兩個集合進行交集運算,可以使用intersection()
方法或者&
運算符。這里有兩種方法:
方法1:使用intersection()
方法
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 使用intersection()方法求交集
intersection_result = set1.intersection(set2)
print(intersection_result) # 輸出:{4, 5}
方法2:使用&
運算符
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 使用&運算符求交集
intersection_result = set1 & set2
print(intersection_result) # 輸出:{4, 5}
這兩種方法都可以求出兩個集合的交集。