set 是一个无序且不重复的元素集合
>>> num = {1,2,3,4,5}
1.add()添加一个元素
>>> num.add(6)
>>> num
>>> {1,2,3,4,5,6}
2.clear()清除集合中所有元素
>>> num.clear()
>>> num
>>> set()
3.copy()复制一个集合
>>> num1 = num.copy()
>>> num1
>>> {1,2,3,4,5}
4.difference()取得集合在一个或多个集合中不同的元素
>>> num1 = {2,4,6,8,10}
>>> num2 = {1,3,11,12,14}
#返回在一个集合中不同的元素
>>> num.difference(num1)
>>> {1,3,5}
#返回在多个集合中不同的元素
>>> num.difference(num1,num2)
>>> {5}
5.difference_update()删除当前集合中所有包含在新集合里的元素
>>> num1 = {2,4,6,8,10}
>>> num2 = {1,2,11,13}
>>> num.difference_update(num1,num2)
>>> num
>>> {3,5}
6.discard()从集合中移除一个元素,如果元素不存在,不做任何处理
>>> num.discard(1)
>>> num
>>> {2,3,4,5}
7.intersection()取交集,新建一个集合
>>> num1 ={1,3,5,7,9}
>>> num.intersection(num1)
>>> {1,3,5}
8.intersection_update()取交集,修改与原来的集合
>>> num1 = {1,3,5,7,9}
>>> num.intersection_update(num1)
>>> num
>>> {1,3,5}
9.isdisjoint()如果没有交集,返回True
>>> num2 ={6,8,10}
>>> num.isdisjoint(num2)
>>> True
10.pop()从集合开头移除一个元素
>>> num.pop()
>>> 1
>>> num
>>> {2,3,4,5}
PS:如果集合为空,返回错误提示
11.symmetric_difference()差集,创建新对象
>>> num = {1,2,3,4,5,6}
>>> num1 = {2,3,4,6,8,9}
>>> num.symmetric_difference(num1)
>>> {1,5,8,9}
12.symmetric_difference_update()差集,改变原来的集合
>>> num = {1,2,3,4,5,6}
>>> num1 = {2,3,4,6,8,9}
>>> num.symmetric_difference_update(num1)
>>> num
>>> {1,5,8,9}
13.union()并集,返回一个新集合
>>> num ={1,2,4,6,7}
>>> num1 ={,2,4,6,8,10,12}
>>> num.union(num1)
>>> {1,2,4,6,7,8,10,12}
14.update()并集,并更新该集合
>>> num ={1,2,4,6,7}
>>> num1 ={,2,4,6,8,10,12}
>>> num.update(num1)
>>> num
>>> {1,2,4,6,7,8,10,12}
小练习:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 old_dict = { 2 "#1": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80}, 3 "#2": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80}, 4 "#3": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80} 5 } 6 new_dict = { 7 "#1": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 800}, 8 "#3": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80}, 9 "#4": {'hostname': 'c2', 'cpu_count': 2, 'mem_capicity': 80} 10 } 11 old_set = set(old_dict.keys()) 12 update_list = list(old_set.intersection(new_dict.keys())) 13 14 new_list = [] 15 del_list = [] 16 17 for i in new_dict.keys(): 18 if i not in update_list: 19 new_list.append(i) 20 for i in old_dict.keys(): 21 if i not in update_list: 22 del_list.append(i) 23 print (update_list,new_list,del_list,new_dict.keys()) 24 print(new_dict)
结果为:
>>> ['#1', '#3'] ['#4'] ['#2'] dict_keys(['#1', '#3', '#4'])
>>>{
'#1': {'mem_capicity': 800, 'hostname': 'c1', 'cpu_count': 2},
'#3': {'mem_capicity': 80, 'hostname': 'c1', 'cpu_count': 2},
'#4': {'mem_capicity': 80, 'hostname': 'c2', 'cpu_count': 2}
}