在Python中,取两个集合的交集可以通过以下几种方法实现:
1. 使用集合的交集操作符 `&`:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection = set1 & set2
print(intersection) 输出:{2, 3}
2. 使用集合的 `intersection()` 方法:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection = set1.intersection(set2)
print(intersection) 输出:{2, 3}
3. 使用 `set.intersection()` 方法,可以传入多个集合作为参数:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
intersection = set1.intersection(set2, set3)
print(intersection) 输出:{2, 3}
4. 如果需要从列表中取交集,可以先将列表转换为集合,然后使用上述方法:
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
intersection = list(set(list1) & set(list2))
print(intersection) 输出:[4, 5]
以上方法都可以用来计算两个集合的交集