Python学习——set集合的补充

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} 小练习:
 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}
}
new_dict = {
"#1": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 800},
"#3": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
"#4": {'hostname': 'c2', 'cpu_count': 2, 'mem_capicity': 80}
}
old_set = set(old_dict.keys())
update_list = list(old_set.intersection(new_dict.keys())) new_list = []
del_list = [] for i in new_dict.keys():
  if i not in update_list:
    new_list.append(i)
for i in old_dict.keys():
  if i not in update_list:
    del_list.append(i)
print (update_list,new_list,del_list,new_dict.keys())
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}
}

上一篇:SLAM中的逆深度参数化


下一篇:入门实战《深度学习技术图像处理入门》+《视觉SLAM十四讲从理论到实践》