python set交集
时间: 2023-11-17 10:57:29 浏览: 34
Python中的set类型提供了intersection()方法来求两个集合的交集。例如,我们有两个集合A和B,可以使用以下代码来求它们的交集:
```
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
C = A.intersection(B)
print(C)
```
输出结果为:
```
{3, 4}
```
相关问题
python set 交集
Python中的set数据类型提供了一个方便的方法来计算两个或多个集合的交集。你可以使用`intersection`方法或`&`运算符来执行这个操作。
以下是使用`intersection`方法的示例:
```python
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
intersection_set = set1.intersection(set2)
print(intersection_set)
```
输出:
```
{4, 5}
```
以下是使用`&`运算符的示例:
```python
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
intersection_set = set1 & set2
print(intersection_set)
```
输出:
```
{4, 5}
```
以上示例中,两个集合的交集是`{4, 5}`。
Python计算交集并集
在Python中,可以使用集合(set)来计算交集和并集。集合是一种无序且不重复的数据结构。
要计算两个集合的交集,可以使用intersection()方法或者使用&运算符。例如:
```python
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# 使用intersection()方法计算交集
intersection_set = set1.intersection(set2)
print(intersection_set) # 输出: {3, 4}
# 使用&运算符计算交集
intersection_set = set1 & set2
print(intersection_set) # 输出: {3, 4}
```
要计算两个集合的并集,可以使用union()方法或者使用|运算符。例如:
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 使用union()方法计算并集
union_set = set1.union(set2)
print(union_set) # 输出: {1, 2, 3, 4, 5}
# 使用|运算符计算并集
union_set = set1 | set2
print(union_set) # 输出: {1, 2, 3, 4, 5}
```