list1 = [1,3,4,7,2,7,10] list1 = set(list1) print(list1,type(list1)) list2 = set([2,4,45,12,35]) print(list2,type(list2)) #交集 print(list1.intersection(list2)) print(list1 & list2) #并集 print(list1.union(list2)) print(list1 | list2) #差集 print(list1.difference(list2)) print(list1 - list2) # in list1 but not in list2 print(list2.difference(list1)) #对称差集,(两个集合并集-交集) print(list1.symmetric_difference(list2)) print(list1^list2) #判断是否是其子集/父集 list3 = set([1,3,10]) print(list3.issubset(list1)) print(list1.issuperset(list3)) #判断两个集合是否有交集 list4 =set([4,5,6]) print(list3.isdisjoint(list4)) #添加 list1.add('0') print(list1) #删除 list1.remove("0") print(list1)
输出结果
"F:pythonpython installvenvScriptspython.exe" F:/python/pyProject/venv/集合 {1, 2, 3, 4, 7, 10} <class 'set'> {2, 35, 4, 12, 45} <class 'set'> {2, 4} {2, 4} {1, 2, 3, 4, 35, 7, 10, 12, 45} {1, 2, 3, 4, 35, 7, 10, 12, 45} {1, 10, 3, 7} {1, 10, 3, 7} {35, 12, 45} {1, 35, 3, 7, 10, 12, 45} {1, 35, 3, 7, 10, 12, 45} True True True {1, 2, 3, 4, '0', 7, 10} {1, 2, 3, 4, 7, 10} Process finished with exit code 0