Python小技巧整理(三)

目录

1.获得两个集合的并集

2.获取两个集合的交集 

3.获得两个集合的差集

4.获得两个集合的对称差集


1.获得两个集合的并集

        初级:遍历这两个集合,将元素添加到一个新的集合中

set_a = {1, 2, 4, 8}  
set_b = {3, 8, 7, 1, 9}  
 
union_set = set()  
 
for i in set_a:  
    union_set.add(i)  

for i in set_b:  
    union_set.add(i)  
 
print(union_set)

# {1, 2, 3, 4, 7, 8, 9}

        进阶:Python中的集合为两个集合的合并提供了一个union() 方法(或update()方法,或 | 符号)

set_a = {1, 2, 4, 8}
set_b = {3, 8, 7, 1, 9}

union_set = set_a.union(set_b)
print(union_set)

# {1, 2, 3, 4, 7, 8, 9}

print(set_a|set_b)

# {1, 2, 3, 4, 7, 8, 9}

set_a.update(set_b)
print(set_a)

# {1, 2, 3, 4, 7, 8, 9}

2.获取两个集合的交集 

        初级:遍历寻找两个集合之间的共同元素

set_a = {1, 2, 4, 8}  
set_b = {3, 8, 7, 1, 9}  
 
intersection_set = set()  
 
for i in set_a:  
    if i in set_b:  
        intersection_set.add(i)  
 
print(intersection_set)  

# {8, 1}

        进阶:Python 为两个集合的交集提供了intersection() 方法(或intersection_update()方法,或&符号)

set_a = {1, 2, 4, 8}  
set_b = {3, 8, 7, 1, 9}  
 
intersection_set = set_a.intersection(set_b)  
print(intersection_set) 

# {8, 1}

print(set_a&set_b)

# {8, 1}

set_a.intersection_update(set_b)
print(set_a)

# {8, 1}

3.获得两个集合的差集

        初级:遍历寻找一个集合中另一集合没有的元素

set_a = {1, 2, 4, 8}  
set_b = {3, 8, 7, 1, 9}  

difference_set = set()  
 
for i in set_a:  
    if i not in set_b:  
        difference_set.add(i)  
 
print(difference_set) 

        进阶:Python 为两个集合的差集提供了difference()方法(或difference_update()方法,或-符号)

set_a = {1, 2, 4, 8}  
set_b = {3, 8, 7, 1, 9}  

difference_set = set_a.difference(set_b)
print(difference_set)

# {2, 4}

print(set_a-set_b)

# {2, 4}

set_a.difference_update(set_b)
print(set_a)

# {2, 4}

4.获得两个集合的对称差集

        初级:遍历两个集合并集中交集没有的元素

set_a = {1, 2, 4, 8}  
set_b = {3, 8, 7, 1, 9}

union_set = set() 
intersection_set = set()  
symmetric_difference_set = set()

for i in set_a:  
    union_set.add(i)  

for i in set_b:  
    union_set.add(i)  

for i in set_a:  
    if i in set_b:  
        intersection_set.add(i) 

for i in union_set:
    if i not in intersection_set:
        symmetric_difference_set.add(i)

print(symmetric_difference_set) 

# {2, 3, 4, 7, 9}

        进阶:Python 为两个集合的对称差集提供了symmetric_difference()方法(或symmetric_difference_update()方法,或^符号)

set_a = {1, 2, 4, 8}  
set_b = {3, 8, 7, 1, 9}

symmetric_difference_set = set_a.symmetric_difference(set_b)
print(symmetric_difference_set)

# {2, 3, 4, 7, 9}

print(set_a^set_b)

# {2, 3, 4, 7, 9}

set_a.symmetric_difference_update(set_b)
print(set_a)

# {2, 3, 4, 7, 9}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值