Python基础入门:集合、字典、函数、模块、文件操作与异常处理
1. Python集合操作
1.1 集合运算
集合在Python中是一种无序且唯一的数据结构,提供了多种运算操作:
- 并集 :两个集合的并集是包含两个集合中所有元素的集合。可以使用 | 运算符或 union() 方法来实现。
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
print "Union of A | B", A|B
# alternative we can use union()
A.union(B)
输出结果:
Union of A | B set([1, 2, 3, 4, 5, 6, 7, 8])
- 交集 :两个集合的交集是包含两个集合中共同元素的集合。可以使用
&运算符或intersection()方法来实现。
# use & operator
print "Intersection of A & B", A & B
# alternative we can use in
超级会员免费看
订阅专栏 解锁全文
20万+

被折叠的 条评论
为什么被折叠?



