集合-多集合操作(交集、并集、差集、判定)

1、交集 intersection

# 交集
a = {'Alex','Bob','Tom','Alice','John'}
b = {'John','Egon','Celia','Alex'}
print(a & b)  # 取交集
c = a.intersection(b)  # 取交集
print(c)

输出:
{'John', 'Alex'}
{'John', 'Alex'}

2、并集 union

# 并集
a = {'Alex','Bob','Tom','Alice','John'}
b = {'John','Egon','Celia','Alex'}
print(a | b)   # 取并集
c = a.union(b)   # 取并集
print(c)

输出:
{'Alice', 'Bob', 'Tom', 'Celia', 'Egon', 'Alex', 'John'}
{'Alice', 'Bob', 'Tom', 'Celia', 'Egon', 'Alex', 'John'}

3、差集 difference

# 差集
a = {'Alex','Bob','Tom','Alice','John'}
b = {'John', 'Egon', 'Celia', 'Alex'}
print(a - b)   # 取差集
c = a.difference(b)  # 取差集
print(c)
# 反向求差集
print(b - a)  # 反向求差集
d = b.difference(a)  # 反向求差集
print(d)

输出:
{'Bob', 'Alice', 'Tom'}
{'Bob', 'Alice', 'Tom'}
{'Egon', 'Celia'}
{'Egon', 'Celia'}

4、判定
1)isdisjoint() 判断 两个集合是否不相交

a = {'Alex','Bob','Tom','Alice','John'}
b = {'John', 'Egon', 'Celia', 'Alex'}
print(a.isdisjoint(b))  # 判断 两个集合是否不相交,不相交返回true,相交返回false

输出:
False

2)issuperset() 判断 一个集合是否包含另一个集合

a = {'Alex','Bob','Tom','Alice','John'}
b = {'John', 'Egon', 'Celia', 'Alex'}
c = {'Alex','Alice'}
d = a.issuperset(b)  # a是不是b的父集
print(d)

d = a.issuperset(c)  # a是不是c的父集
print(d)

输出:
False
True

3)issubset() 判断 一个集合是否包含于另一个集合

a = {'Alex','Bob','Tom','Alice','John'}
b = {'John', 'Egon', 'Celia', 'Alex'}
c = {'Alex','Alice'}
d = a.issubset(b)  # a是不是b的子集(即a里的每个值都在b里存在)
print(d)

e = c.issubset(a)  # c是不是a的子集
print(e)

输出:
False
True
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值