python如何求两个集合的交集
时间: 2023-10-11 13:05:56 浏览: 66
Python中可以使用&操作符或者intersection()方法来求两个集合的交集。
示例代码如下:
```python
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 使用&操作符求交集
intersect = set1 & set2
print(intersect)
# 使用intersection()方法求交集
intersect = set1.intersection(set2)
print(intersect)
```
输出:
```
{4, 5}
{4, 5}
```
以上代码中,我们定义了两个集合set1和set2,并使用&操作符和intersection()方法求它们的交集。最终输出的结果都是{4, 5}。
相关问题
python求两个集合的交集
你可以使用 & 运算符或 intersection() 方法来求两个集合的交集,如下所示:
```python
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 使用 & 运算符求交集
intersection = set1 & set2
print(intersection) # {4, 5}
# 使用 intersection() 方法求交集
intersection = set1.intersection(set2)
print(intersection) # {4, 5}
```
以上代码中,我们创建了两个集合 set1 和 set2,然后使用 & 运算符和 intersection() 方法求它们的交集。最后打印输出交集的结果。
python两个集合取交集高效代码实现
以下是一种高效的Python代码实现两个集合取交集的方法:
```python
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
intersection = set1 & set2
print(intersection) # 输出:{4, 5}
```
这段代码使用了Python中的集合操作符`&`来计算两个集合的交集。通过将两个集合使用`&`操作符连接起来,我们可以得到它们的交集。