在Python3中,集合(set)是一种无序的、可变的、不重复的数据结构,用于存储唯一的元素。集合是由花括号 {} 创建的,或者使用 set() 构造函数。以下是关于Python3集合的基本操作:

1. 创建集合
my_set = {1, 2, 3, 4, 5}

2. 添加元素
my_set.add(6)  # 添加单个元素
my_set.update([7, 8, 9])  # 添加多个元素

3. 删除元素
my_set.remove(3)  # 删除指定元素,如果元素不存在会引发错误
my_set.discard(3)  # 删除指定元素,如果元素不存在不会引发错误
my_set.pop()  # 删除并返回任意一个元素

4. 集合操作

4.1 并集
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2  # 或者使用 set1.union(set2)

4.2 交集
intersection_set = set1 & set2  # 或者使用 set1.intersection(set2)

4.3 差集
difference_set = set1 - set2  # 或者使用 set1.difference(set2)

4.4 对称差集
symmetric_difference_set = set1 ^ set2  # 或者使用 set1.symmetric_difference(set2)

5. 成员关系检测
element_exists = 3 in my_set  # 检查元素是否存在于集合中

6. 遍历集合
for element in my_set:
    print(element)

7. 集合推导式
squared_set = {x**2 for x in range(5)}  # 集合推导式

集合是一种非常有用的数据结构,特别适用于去重和成员关系检测。


转载请注明出处:http://www.zyzy.cn/article/detail/204/Python3