码迷,mamicode.com
首页 > 其他好文 > 详细

集合与字符串格式化

时间:2018-06-19 13:39:44      阅读:328      评论:0      收藏:0      [点我收藏+]

标签:int()   diff   amp   mat   不可变   hash   unset   差集   name   

一、集合(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)

 

 

 

集合与字符串格式化

标签:int()   diff   amp   mat   不可变   hash   unset   差集   name   

原文地址:https://www.cnblogs.com/qiuchen2018/p/9197809.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!