Python之路【第三篇】:Python基础(10)——set集合

# 练习:寻找差异
# # 数据库中原有
old_dict = {
"#1":8,
"#2":4,
"#4":2,
}
#
# cmdb 新汇报的数据
new_dict = {
"#1":4,
"#2":4,
"#3":2,
}
#
# 需要删除:?
# 分析:
# 1、需要删除的数据,即old_dict中有的,new_dict中没有的,就是代表已经过时的数据,就是我们需要删除的。
# 即只要找到字典中的key就行,key在字典中有唯一性。
# 上面学到的set集合就带了这样的功能,我们只要拿到key的数据放到set集合中,就能实现我们的需求。
# 2、但是set集合只能处理元素,不能处理字典。所以我们需要将字典里面的key先提取出来,使用dict字典的内置方法keys()
# ( 7 radiansdict.keys() 以列表返回一个字典所有的键)
old_keys = old_dict.keys()
new_keys = new_dict.keys()
# print(old_keys)
# 输出
# dict_keys(['#1', '#4', '#2'])
# print(type(old_keys))
# 输出
# <class 'dict_keys'>

# 3、将来列表转换成集合
old_set = set(old_keys)
## old_set = set(old_dict.keys())
new_set = set(new_keys)
## new_set = set(new_dict.keys())
# print(old_set)
# print(type(old_set))
# 输出
# {'#1', '#2', '#4'}
# <class 'set'>
# print(new_set)
# print(type(new_set))
# # 输出
# {'#3', '#2', '#1'}
# <class 'set'>
# 4、通过set集合的difference方法, old_set中存在,new_set中不存在的,得到应该删除的数据
remove_set = old_set.difference(new_set)
# print(remove_set)
# 结果
# {'#4'}


# 需要新建:?
# 分析:new_set中存在的,old_set中不存在的,就是需要新建的, 还是用difference方法,将A和B反过来。
add_set = new_set.difference(old_dict)
# print(add_set)
# 结果
# {'#3'}

# 需要更新:?
# 分析:old_set和new_set相同都有的就是需要更新的,谁在前面都可以。取交集,使用intersection()方法
update_set = old_set.intersection(new_set)
# print(update_set)
# 结果
# {'#1', '#2'}




# 交集
# def intersection(self, *args, **kwargs): # real signature unknown
# """
# Return the intersection of two sets as a new set. 交集
#
# (i.e. all elements that are in both sets.)
# """
# pass

# s1 = {11,22,33}
# s2 = {22,33,44}
# s3 = s1.intersection(s2)
# print(s3)
# 输出
# {33, 22}
原文地址:https://www.cnblogs.com/jiangnanmu/p/5536691.html