集合(Sets)是 Python 中的一个内置数据类型,用于存储不重复的元素。它们在处理数学集合操作时非常有用,例如并集、交集、差集等。
集合创建
要创建一个集合,可以使用花括号 {}
或者内置的 set()
函数。
# 使用花括号
my_set = {1, 2, 3, 4, 5}
# 使用 set() 函数
my_set = set([1, 2, 3, 4, 5])
集合操作
以下是一些常见的集合操作:
并集(Union):使用
|
操作符或者union()
方法。set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1 | set2 # 或者 set1.union(set2)
交集(Intersection):使用
&
操作符或者intersection()
方法。intersection_set = set1 & set2 # 或者 set1.intersection(set2)
差集(Difference):使用
-
操作符或者difference()
方法。difference_set = set1 - set2 # 或者 set1.difference(set2)
对称差集(Symmetric Difference):使用
^
操作符或者symmetric_difference()
方法。symmetric_difference_set = set1 ^ set2 # 或者 set1.symmetric_difference(set2)
集合方法
add(element)
: 添加一个元素。remove(element)
: 移除一个元素,如果元素不存在则引发错误。discard(element)
: 移除一个元素,如果元素不存在则不执行任何操作。update(iterable)
: 将可迭代对象的所有元素添加到集合中。difference_update(iterable)
: 从集合中移除所有可迭代对象中的元素。
示例
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print("并集:", set1 | set2)
print("交集:", set1 & set2)
print("差集:", set1 - set2)
print("对称差集:", set1 ^ set2)
更多关于 Python 集合的信息,可以参考本站的 Python 集合详细指南。
集合应用
集合在编程中有很多应用场景,例如:
- 去重:当你需要从列表中去除重复元素时。
- 集合操作:在处理数学问题或算法时。
- 数据校验:用于检查数据是否满足特定条件。
希望这个教程能帮助你更好地理解和使用 Python 集合。🤗
<center><img src="https://cloud-image.ullrai.com/q/python_sets/" alt="Python Sets"/></center>