Python现场操作
示例
与其他套装
#路口
{1, 2, 3, 4, 5}.intersection({3, 4, 5, 6}) #{3,4,5}
{1, 2, 3, 4, 5} & {3, 4, 5, 6} #{3,4,5}
#联盟
{1, 2, 3, 4, 5}.union({3, 4, 5, 6}) #{1,2,3,4,5,6}
{1, 2, 3, 4, 5} | {3, 4, 5, 6} #{1,2,3,4,5,6}
#区别
{1, 2, 3, 4}.difference({2, 3, 5}) #{1,4}
{1, 2, 3, 4} - {2, 3, 5} #{1,4}
#与的对称差异
{1, 2, 3, 4}.symmetric_difference({2, 3, 5}) #{1,4,5}
{1, 2, 3, 4} ^ {2, 3, 5} #{1,4,5}
#超集检查
{1, 2}.issuperset({1, 2, 3}) #假
{1, 2} >= {1, 2, 3} #假
#子集检查
{1, 2}.issubset({1, 2, 3}) #真正
{1, 2} <= {1, 2, 3} #真正
#脱节支票
{1, 2}.isdisjoint({3, 4}) #真正
{1, 2}.isdisjoint({1, 4}) #假单元素
#存在检查
2 in {1,2,3} #真正
4 in {1,2,3} #假
4 not in {1,2,3} #真正
#添加和删除
s = {1,2,3}
s.add(4) #s=={1,2,3,4}
s.discard(3) #s=={1,2,4}
s.discard(5) #s=={1,2,4}
s.remove(2) #s=={1,4}
s.remove(2) #KeyError!集合操作返回新集合,但具有相应的就地版本:
例如:
s = {1, 2}
s.update({3, 4}) #s=={1,2,3,4}