运用python求以下两个集合的交集、并集、差集和对称差集setA={1,2,34,5,3}setB={22,3,1,5,6}
时间: 2023-10-09 22:05:37 浏览: 364
可以使用 Python 的集合操作符来求解集合的交集、并集、差集和对称差集。
交集可以使用 & 符号或者 intersection() 函数来求解:
```
setA = {1, 2, 34, 5, 3}
setB = {22, 3, 1, 5, 6}
intersection = setA & setB
print(intersection)
intersection = setA.intersection(setB)
print(intersection)
```
输出:
```
{1, 3, 5}
{1, 3, 5}
```
并集可以使用 | 符号或者 union() 函数来求解:
```
setA = {1, 2, 34, 5, 3}
setB = {22, 3, 1, 5, 6}
union = setA | setB
print(union)
union = setA.union(setB)
print(union)
```
输出:
```
{1, 2, 34, 3, 5, 6, 22}
{1, 2, 34, 3, 5, 6, 22}
```
差集可以使用 - 符号或者 difference() 函数来求解:
```
setA = {1, 2, 34, 5, 3}
setB = {22, 3, 1, 5, 6}
difference = setA - setB
print(difference)
difference = setA.difference(setB)
print(difference)
```
输出:
```
{2, 34}
{2, 34}
```
对称差集可以使用 ^ 符号或者 symmetric_difference() 函数来求解:
```
setA = {1, 2, 34, 5, 3}
setB = {22, 3, 1, 5, 6}
symmetric_difference = setA ^ setB
print(symmetric_difference)
symmetric_difference = setA.symmetric_difference(setB)
print(symmetric_difference)
```
输出:
```
{2, 34, 6, 22}
{2, 34, 6, 22}
```
阅读全文