python集合set,交集,并集,差集,对称差集,子集和超集

x = {1, 2, 3, 4}
y = {2, 4, 5, 6} # 交集(取x中与y中相同部分)
print(x.intersection(y))
print(x & y) # 并集(去重合并)
print(x.union(y))
print(x | y) # 差集(x在y中不同部分,相反)
print(x.difference(y)) # {1, 3}
print(y.difference(x)) # {5,6}
print(x - y)
print(y - x) # 补(对称差集) 两个分别差集之后合并为一个集合
print(x.symmetric_difference(y))
print(y.symmetric_difference(x))
print(x ^ y)
print(y ^ x) # 子集和超集 :超集长的中包含短的。子集,短的在长的中
print(x.issubset(y))
print(y.issuperset(x))

结果请对号入座:

x.intersection(y):{2, 4}
x & y:{2, 4}
x.union(y):{1, 2, 3, 4, 5, 6}
x | y:{1, 2, 3, 4, 5, 6}
x.difference(y):{1, 3}
y.difference(x):{5, 6}
x - y:{1, 3}
y - x:{5, 6}
x.symmetric_difference(y):{1, 3, 5, 6}
y.symmetric_difference(x):{1, 3, 5, 6}
x ^ y:{1, 3, 5, 6}
y ^ x:{1, 3, 5, 6}
x.issubset(y):False
y.issuperset(x):False
04-30 05:58