集合与字符串格式化

一、集合(set)

1、基本概念

1)定义

集合:由不同元素组成,无序,集合中元素必须为不可变类型(可hash)。

2)创建

a)直接创建

s = { }

b)set

s = set( )

2、集合函数

1)add():增加集合元素

2)clear()

3)copy()

4)pop():随机删除一个元素

      remove():指定删除某个元素,若元素不存在则报错

      discard():指定删除某个元素,若元素不存在时不报错

5)intersection()  &:交集

6)union()  |:并集

7)difference()  -:差集

8)symmetric_difference()  ^:交叉补集

9)isdisjoint():判断是否存在交集,不存在为True

10)issunset():判断s1是否为s2的子集

11)update():更新

二、字符串格式化

1、%

%s:可传递任何类型的参数(万能),但可读性差

%d:数字

%.2f:浮点数

"i am %(name)s %(age)d" % {"name":"alex","age":18}

2、format

format()的参数与前面一一对应,否则报错

*:与列表相关  **:与字典相关

print("i am {} age{}".format("alex,18"))
#字典
print("i am {} age{}".format("name" = "alex","age" = 18))
print("i am {} age{}".format(**{"name":"alex","age":18})
#列表
print("i am {}{}{}".format(1,2,3)
print("i am {}{}{}".format(*[1,2,3])

练习

寻找差异

# 数据库中原有
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': '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)
new_set = set(new_dict)

del_set = old_set.difference(new_set)
add_set = old_set.union(new_set)
intersec_set = old_set.intersection(new_set)

#删除
del_set = old_set.difference(new_set)    #删除的元素
old_set = old_set.intersection(new_set)

#更新
update_set = new_set.difference(old_set)     #更新的元素
old_set = old_set.union(new_set)
 

猜你喜欢

转载自www.cnblogs.com/qiuchen2018/p/9197809.html
今日推荐