1、定义
list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_2 =set([2,6,0,66,22,8,4])print(list_1,list_2)
打印输出结果:
{1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 8, 22}
2、交集
list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_2 =set([2,6,0,66,22,8,4])print( list_1.intersection(list_2) )print(list_1 & list_2)
打印输出结果:
{4, 6}{ 4, 6}
3、并集
list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_2 =set([2,6,0,66,22,8,4])print(list_1.union(list_2))print(list_1 | list_2)
打印输出结果:
{0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}{0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}
4、 差集 in list_1 but not in list_2
list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_2 =set([2,6,0,66,22,8,4])print(list_1.difference(list_2))print(list_1 - list_2)
打印输出结果:
{1, 3, 5, 7, 9}{ 1, 3, 5, 7, 9}
5、差集 in list_2 but not in list_1
list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_2 =set([2,6,0,66,22,8,4])print(list_2.difference(list_1))print(list_2 - list_1)
打印输出结果:
{0, 2, 66, 8, 22}{0, 2, 66, 8, 22}
6、子集
list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_3 = set([1,3,7])print(list_3.issubset(list_1))
打印输出结果:
True
7、超集
list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_3 = set([1,3,7])print(list_1.issuperset(list_3))
打印输出结果:
True
8、对称差集
list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_2 =set([2,6,0,66,22,8,4])print(list_1.symmetric_difference(list_2))print(list_1 ^ list_2)
打印输出结果:
{0, 1, 2, 66, 3, 5, 7, 8, 9, 22}{0, 1, 2, 66, 3, 5, 7, 8, 9, 22}
9、判断是否有相同项,没有则返回true
list_3 = set([1,3,7])list_4 = set([5,6,7,8])print(list_3.isdisjoint(list_4))
打印输出结果:
False
10、add()与update
list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)list_1.add(999)list_1.update([888, 777, 555])print(list_1)
打印输出结果:
{1, 3, 4, 5, 6, 7, 999, 9, 777, 555, 888}
11、pop()
list_1 = [1,4,5,7,3,6,7,9]list_1 = set(list_1)print(list_1.pop())print(list_1.pop())print(list_1.pop())print(list_1.pop())print(list_1)
打印输出结果:
1345{ 6, 7, 9}
12、discard()
list_1 = [1,4,5,7,3,6,7,9,888]list_1 = set(list_1)print( list_1.discard(888) )print(list_1)
打印输出结果:
None{ 1, 3, 4, 5, 6, 7, 9}