set() python
时间: 2023-11-21 14:55:29 浏览: 35
`set()`是Python中的一种数据类型,它是一个无序、不重复的集合。可以使用`set()`函数来创建一个空的集合,也可以使用一对花括号`{}`来创建一个包含元素的集合。下面是一些关于`set()`的用法和示例代码:
1. 创建一个空的集合
```python
my_set = set()
```
2. 创建一个包含元素的集合
```python
my_set = {1, 2, 3}
```
3. 向集合中添加元素
```python
my_set.add(4)
```
4. 从集合中删除元素
```python
my_set.remove(3)
```
5. 检查集合中是否包含某个元素
```python
if 2 in my_set:
print("2 is in the set")
```
6. 求两个集合的交集
```python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection = set1.intersection(set2)
print(intersection) # 输出:{2, 3}
```
7. 求两个集合的并集
```python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
union = set1.union(set2)
print(union) # 输出:{1, 2, 3, 4}
```
8. 求两个集合的差集
```python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
difference = set1.difference(set2)
print(difference) # 输出:{1}
```