python集合求交集
时间: 2023-11-04 09:19:08 浏览: 46
要在Python中求两个集合的交集,可以使用`intersection`方法或`&`运算符。下面是一个示例代码:
```python
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection = set1.intersection(set2)
print(intersection)
```
输出结果为:`{3, 4}`
你也可以使用运算符`&`来实现相同的效果:
```python
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection = set1 & set2
print(intersection)
```
输出结果同样为:`{3, 4}`
相关问题
python求集合的交集
可以使用 Python 内置函数 set 的交集方法 & 来求两个集合的交集,例如:
```python
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection = set1 & set2
print(intersection)
```
输出:{3, 4}
Python集合的交集
Python中可以使用`&`符号或者`intersection()`方法来求两个集合的交集。
示例代码:
```python
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection = set1 & set2 # 使用 & 符号求交集
print(intersection) # 输出 {3, 4}
intersection = set1.intersection(set2) # 使用 intersection() 方法求交集
print(intersection) # 输出 {3, 4}
```