简介:本文将详细介绍Python 3中集合(set)的各种操作,包括创建、添加、删除、交集、并集、差集、对称差集等操作,帮助读者更好地理解和使用集合。
在Python 3中,集合(set)是一种无序且不重复的数据结构,常用于去重、关系测试及集合运算等场景。本文将详细讲解Python 3中集合的各种操作,包括创建、添加、删除、交集、并集、差集、对称差集等。
在Python 3中,可以使用大括号 {} 或 set() 函数来创建集合。例如:
# 使用大括号创建集合my_set1 = {1, 2, 3, 4}print(my_set1) # 输出:{1, 2, 3, 4}# 使用set()函数创建集合my_set2 = set([1, 2, 2, 3, 4, 4])print(my_set2) # 输出:{1, 2, 3, 4},注意集合中的元素不重复
可以使用 add() 方法向集合中添加单个元素,或使用 update() 方法添加多个元素。例如:
my_set = {1, 2, 3}# 使用add()方法添加单个元素my_set.add(4)print(my_set) # 输出:{1, 2, 3, 4}# 使用update()方法添加多个元素my_set.update([5, 6, 7])print(my_set) # 输出:{1, 2, 3, 4, 5, 6, 7}
可以使用 remove() 方法删除集合中的单个元素,或使用 discard() 方法尝试删除元素(如果元素不存在则忽略)。此外,还可以使用 pop() 方法随机删除并返回一个元素,或使用 clear() 方法清空整个集合。例如:
my_set = {1, 2, 3, 4, 5}# 使用remove()方法删除元素my_set.remove(3)print(my_set) # 输出:{1, 2, 4, 5}# 使用discard()方法尝试删除元素my_set.discard(6) # 忽略,因为6不在集合中print(my_set) # 输出:{1, 2, 4, 5}# 使用pop()方法随机删除并返回一个元素removed_element = my_set.pop()print(removed_element) # 输出:随机的一个元素,如5print(my_set) # 输出:{1, 2, 4}# 使用clear()方法清空集合my_set.clear()print(my_set) # 输出:set()
Python 3中的集合还支持多种集合运算,包括交集、并集、差集和对称差集。这些运算可以通过相应的操作符或方法来实现。例如:
```python
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection = set1 & set2
print(intersection) # 输出:{3, 4}
intersection = set1.intersection(set2)
print(intersection) # 输出:{3, 4}
union = set1 | set2
print(union) # 输出:{1, 2, 3, 4, 5, 6}
union = set1.union(set2)
print(union) # 输出:{1, 2, 3, 4, 5, 6}
difference = set1 - set2
print(difference) # 输出:{1, 2}
difference = set1.difference(set2)
print(difference) # 输出:{1, 2}
symmetric_difference = set1 ^ set2
print(symmetric_difference)