在 Python 中,集合(set)是一种无序、可变、不重复的数据容器。它提供了丰富的操作方法,支持成员判断、增删改查、集合运算等。
掌握这些操作,可以更高效地使用集合处理数据。
一、访问与遍历
1、成员运算
使用 in 和 not in 判断元素是否存在:
s = {1, 2, 3}
print(2 in s) # True
print(5 not in s) # True2、遍历集合
集合是可迭代对象,可以直接用 for 循环:
fruits = {"apple", "banana", "cherry"}
for f in fruits:
print(f)注意:集合是无序的,遍历顺序不固定。
二、集合运算
集合支持数学意义上的集合运算。
a = {1, 2, 3}
b = {3, 4, 5}1、并集(union)
print(a | b) # {1, 2, 3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5}2、交集(intersection)
print(a & b) # {3}
print(a.intersection(b)) # {3}3、差集(difference)
print(a - b) # {1, 2},存在于 a 不存在于 b
print(a.difference(b)) # 等价写法4、对称差集(symmetric difference)
print(a ^ b) # {1, 2, 4, 5},只在一个集合中出现
print(a.symmetric_difference(b)) # {1, 2, 4, 5}三、集合修改操作
1、添加元素
s = {1, 2}
s.add(3)
print(s) # {1, 2, 3}2、批量添加
s = {1, 2}
s.update([3, 4, 5])
print(s) # {1, 2, 3, 4, 5}3、删除元素
s = {1, 2}
s.remove(2) # 若不存在会报错
s.discard(10) # 不存在也不会报错
print(s)4、随机删除并返回
s = {1, 2}
val = s.pop()
print(val, s)5、清空集合
s = {1, 2}
s.clear()
print(s) # set()四、关系测试
1、子集
a = {1, 2}
b = {1, 2, 3}
print(a <= b) # True
print(a.issubset(b)) # True2、超集
a = {1, 2}
b = {1, 2, 3}
print(b >= a) # True
print(b.issuperset(a)) # True3、是否无交集
a = {1, 2}
b = {1, 2, 3}
c = {4, 5}
print(a.isdisjoint(c)) # True提示:
集合关系可以用逻辑运算符表示,更简洁:
a = {1, 2}
b = {1, 2, 3}
print(a < b) # True (严格子集)
print(a <= b) # True (子集)
print(b > a) # True (严格超集)
print(a == b) # False五、使用内置函数和方法
1、内置函数
许多内置函数可直接用于集合对象:
s = {5, 2, 9, 1}
print(len(s)) # 4
print(max(s)) # 9
print(min(s)) # 1
print(sum(s)) # 17
print(sorted(s)) # [1, 2, 5, 9],返回列表2、set 类的方法
集合提供了大量方法(如 add()、update()、remove() 等)。
详情请参阅:
⚠️常见操作误区
1、集合不支持索引或切片
s = {1, 2, 3}
# print(s[0]) # ❌ TypeError2、集合无序性
遍历或打印时的顺序不可预测。
小结
基本操作:成员判断、遍历
集合运算:并集、交集、差集、对称差集
修改操作:add()、update()、remove()、discard()、pop()、clear()
关系测试:issubset()、issuperset()、isdisjoint() 或 <, <=, >, >=
内置函数:len()、sum()、max()、min()、sorted()
注意:集合无序,不能索引或切片。
“点赞有美意,赞赏是鼓励”
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.