python中的set函数怎么使用
时间: 2023-05-18 13:04:06 浏览: 88
set函数用于创建一个无序不重复元素集,可以通过以下方式使用:
1. 创建一个空的set:
```
my_set = set()
```
2. 从一个序列创建set:
```
my_set = set([1, 2, 3])
```
3. 添加元素到set:
```
my_set.add(4)
```
4. 删除set中的元素:
```
my_set.remove(3)
```
5. 求两个set的交集:
```
set1 = set([1, 2, 3])
set2 = set([2, 3, 4])
intersection = set1.intersection(set2)
```
6. 求两个set的并集:
```
set1 = set([1, 2, 3])
set2 = set([2, 3, 4])
union = set1.union(set2)
```
7. 求两个set的差集:
```
set1 = set([1, 2, 3])
set2 = set([2, 3, 4])
difference = set1.difference(set2)
```
阅读全文