Home >Backend Development >Python Tutorial >Is set not commonly used in python?
Set is similar to dict. It is also a collection of keys, but does not store value. Since keys cannot be repeated, there are no repeated keys in the set. The set() function creates an unordered set of non-repeating elements, which can be used to test relationships, delete duplicate data, and calculate intersections and differences. , union, etc.
set Syntax:
class set([iterable])
Parameter description: iterable -- iterable object object;
set collection is an unordered and A set of non-repeating elements #set is an unordered and non-repeating set of elements
s1=set() s1.add("alex") s1.add("eric") print(s1) #访问速度快 #天生解决了重复问题 ll=[1,2,3,4,5,6,3,2,1] s2=set(ll) print("转换后的集合为:",s2) #去除相同项,生成一个新的集合,删除 s3=s2.difference([1,2,3,11]) print("s2不变:",s2) print("观察是否生成一个新的集合s3:",s3) s4=s2.difference_update([3,4,5,11]) #删除所有包含在新集合中的元素,并生成一个新的集合 print("是否改变原集合s2:",s2) print("是否生成新集合s4:",s4) ret=s2.pop() #取出元素,并赋值给ret print("移除s2中的一个元素",s2) print("测试pop是否有返回值,移除的元素是:",ret) ret1=s2.remove(2) #必须带参数且没有返回值 print("移除s2中的一个元素:",s2) print("测试remove是否有返回值:",ret1) #练习 # 数据库中原有 old_dict = { "#1":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 80 }, "#2":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 80 }, "#3":{ 'hostname':"c1", 'cpu_count': 2, 'mem_capicity': 80 } } # cmdb 新汇报的数据 new_dict = { "#1":{ 'hostname':"c2", 'cpu_count': 2, 'mem_capicity': 800 }, "#3":{ 'hostname':"c2", 'cpu_count': 2, 'mem_capicity': 80 }, "#4":{ 'hostname':"c2", 'cpu_count': 2, 'mem_capicity': 80 } } """ 分析: 1、新有,原来无→新加入 2、新有,原来有→更新 3、新无,原来有→原来删除 使用set的交集和差集来计算 old_dict.keys() new_dict.keys() 交集(更新):要更新的数据 差集(删除):old_dict.keys()--交集 差集(添加):new_dict.keys()--交集 """ 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) #需要添加的集合
The above is the detailed content of Is set not commonly used in python?. For more information, please follow other related articles on the PHP Chinese website!