这是一个关于 Python 集合的教程集合。Python 集合是一种可以存储多个不同元素的数据结构,这些元素可以是不同的数据类型。
Python 集合特点
- 无序:集合中的元素没有特定的顺序。
- 唯一性:集合中的元素是唯一的,即不会有重复的元素。
使用集合
你可以使用大括号 {}
或者 set()
函数来创建一个集合。
my_set = {1, 2, 3, 4, 5}
或者
my_set = set([1, 2, 3, 4, 5])
集合操作
以下是一些常见的集合操作:
- 添加元素:使用
add()
方法。
my_set.add(6)
- 删除元素:使用
remove()
方法。
my_set.remove(2)
- 查找元素:使用
in
关键字。
print(3 in my_set) # 输出 True
- 集合合并:使用
union()
方法。
another_set = {4, 5, 6, 7}
merged_set = my_set.union(another_set)
- 集合交集:使用
intersection()
方法。
common_elements = my_set.intersection(another_set)
- 集合差集:使用
difference()
方法。
diff_elements = my_set.difference(another_set)
更多关于 Python 集合的详细信息,请参阅 Python 集合教程。
图片示例
下面是 Python 集合的一个简单示例。