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

2021/9/11 23:36:36

本文主要是介绍集合-多集合操作(交集、并集、差集、判定),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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


这篇关于集合-多集合操作(交集、并集、差集、判定)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程