python中集合的用法示例
时间: 2023-09-15 15:24:49 浏览: 94
当应用于集合时,Python提供了多种方法来操作和使用集合。以下是一些示例:
1. 创建集合:
```python
my_set = {1, 2, 3} # 使用花括号创建一个包含元素的集合
print(my_set) # 输出结果:{1, 2, 3}
```
2. 添加元素到集合:
```python
my_set.add(4) # 使用add()方法添加单个元素到集合
print(my_set) # 输出结果:{1, 2, 3, 4}
my_set.update([5, 6]) # 使用update()方法添加多个元素到集合
print(my_set) # 输出结果:{1, 2, 3, 4, 5, 6}
```
3. 移除元素从集合:
```python
my_set.remove(3) # 使用remove()方法移除指定元素
print(my_set) # 输出结果:{1, 2, 4, 5, 6}
my_set.discard(2) # 使用discard()方法移除指定元素
print(my_set) # 输出结果:{1, 4, 5, 6}
popped_element = my_set.pop() # 使用pop()方法移除并返回任意元素
print(popped_element) # 输出结果:1
print(my_set) # 输出结果:{4, 5, 6}
```
4. 集合运算:
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) # 使用union()方法取两个集合的并集
print(union_set) # 输出结果:{1, 2, 3, 4, 5}
intersection_set = set1.intersection(set2) # 使用intersection()方法取两个集合的交集
print(intersection_set) # 输出结果:{3}
difference_set = set1.difference(set2) # 使用difference()方法取两个集合的差集
print(difference_set) # 输出结果:{1, 2}
symmetric_difference_set = set1.symmetric_difference(set2) # 使用symmetric_difference()方法取两个集合的对称差集
print(symmetric_difference_set) # 输出结果:{1, 2, 4, 5}
```
以上是一些集合的基本用法示例,你可以根据需要进一步探索集合的更多用法和功能。
阅读全文
相关推荐








