li=[1,2,3,4,5,6,3,2,1] s2 = set (LI) print (set (LI)) #difference () Remove the same item, generate a new collection, delete s3=s2.difference ([1,2,3,11]) Set1 = { 1,44,87,23,55} Set2 = {1,44,88,23,67}# difference () compare element Set1 There is no ret in Set2 = Set1.difference (set2) print (ret) #{55, and the PR int (set1) print (Set2) #difference_update () deletes the same element in the two set--#从set1中删除和set2中相同的元素 set1.difference_update (set2) print ( Set1) print (Set2) #discard (valyes) remove element # Removes the specified element without error, remove () does not exist error, recommended discard Set1.discard (4) print (SET1) # Intersection () takes the intersection value Set1 = {1,44,87,23,55}set2 = {1,44,88,23,67} ret = set1.intersection (set2) print (Set1) #intersection_ Difference () takes the intersection and updates the # Fetch intersection and updates to Set1 in Set1.intersection_update (set2) print (Set1) #symmetric_difference () symmetric intersection # symmetric intersection, Takes two non-existent elements in the set, generating a new set ret = Set1.symmetric_difference (set2) print (ret) #{67, in., 88}symmetric_difference_update () The symmetric intersection and update set1.symmetric_difference_update (Set2) #对称交集, and update the element to Set1 in the print (Set1) #union () and set and update to the new collection in RET = Set1.union ( Set2) Print (ret) # The original old_dict = {"#1" in the database: {' hostname ': ' C1 ', ' Cpu_count ': 2, ' Mem_cApicity ': "," #2 ": {' hostname ':" C1 ", ' Cpu_count ': 2, ' mem_capicity ': +}, ' #3 ': {' hostname ': ' C1 ', ' Cpu_count ': 2 , ' mem_capicity ': New data reported by}}# CMDB new_dict = {"#1": {' hostname ': ' C2 ', ' Cpu_count ': 2, ' mem_capicity ': +, ' #3 ' : {' hostname ': ' C2 ', ' Cpu_count ': 2, ' mem_capicity ': +}, ' #4 ': {' hostname ': ' C2 ', ' Cpu_count ': 2, ' mem_capicity ': 80}} "" "Analysis: 1, the new has, originally no → New add 2, the new has, originally has → Update 3, the new none, originally had → Original delete uses set intersection and difference set to calculate Old_dict.keys () New_dict.keys () intersection (UPDATE): The data Difference set to update (delete): Old_ Dict.keys ()--intersection difference set (add): New_dict.keys ()--intersection "" "Old=set (Old_dict.keys ()) New=set (New_dict.keys ()) up_set= Old.intersection (new) #需要更新的集合del_set =old.symmetric_difference (up_set) #需要删除的集合add_set =new.symmetric_difference ( Up_set) #需要添加的集合print (up_set) print (del_set) print (Add_set)
Python basic data Type Set method overview