首页 > 代码库 > python 运维自动化之路 Day3
python 运维自动化之路 Day3
学习内容:
1、集合
2、文件操作
3、字符转编码操作
4、函数介绍
5、作用域、局部与全局变量
6、递归
7、函数式编程介绍
8、高阶函数
1、集合
集合是Python常用的数据类型,集合也是无序的。
特性:去重复
关系测试
格式:set([])
去重复,例如:
a= set([1,2,2,3,3,4,4,]) #集合具有天生去重复的特性!集合的格式:set([]) print (a)
打印结果:
C:\Users\hca006\AppData\Local\Programs\Python\Python36\python.exe "D:/python app/var/day3/集合.py" {1, 2, 3, 4} Process finished with exit code 0
关系测试:
交集(intersection)-变量可无前后顺序
a= set([1,2,2,3,3,4,4,]) #集合具有天生去重复的特性!集合的格式:set([]) b= set([3,4,5,6,7]) print(a.intersection(b)) #intersection 交集 print(a&b) #intersection 交集 符号&表示法!
打印结果:
{3, 4}
{3, 4}
并集(union)-变量可无前后顺序
print(a|b) # 并集,管道符表示(|) print(b|a) # 可无前后顺序 print(a.union(b)) # 并集,union 打印结果: {1, 2, 3, 4, 5, 6, 7} {1, 2, 3, 4, 5, 6, 7} {1, 2, 3, 4, 5, 6, 7}
差集(difference)-变量有前后顺序,in list1 not in list2
print(a.difference(b)) # 差集,去掉交集后的值,有前后顺序 print(b.difference(a)) # 差集,去掉交集后的值,有前后顺序 print(a-b) #减号表示(-) 打印结果: {1, 2} {5, 6, 7} {1, 2}
子集(issubset)和父集(issuperset) 返回结果为布尔值。
a= set([1,2,2,3,3,4,4,]) #集合具有天生去重复的特性!集合的格式:set([]) b= set([3,4,5,6,7]) list=[1,2,3] c=set(list) print(c.issubset(a)) # 子集 print (c<=a) # 子集的符号表示法 print(a.issuperset(c)) # 父集 print(a>=c) # 父集的符号表示法 打印结果: True True True True
对称差集(symmetric_difference)-变量无前后顺序
a= set([1,2,2,3,3,4,4,]) #集合具有天生去重复的特性!集合的格式:set([]) b= set([3,4,5,6,7]) list=[1,2,3] c=set(list) print(a ^ b) # 对称差集 用符号^表示 print(b ^ a) # 对称差集 无前后顺序 print(a.symmetric_difference(b)) # 对称差集(理解为去掉交集后的并集) 打印结果: {1, 2, 5, 6, 7} {1, 2, 5, 6, 7} {1, 2, 5, 6, 7}
isdisjoint-判断是否有交集,返回布尔值
print(c.isdisjoint(b))
# 判断两个集合有没有交集,有交集返回False,无交集返回True.
打印结果: False
集合的添加删除
c.add(4) # 添加1项 c.update([‘wjy‘,6,9]) # 添加多项,注意多项是列表的形式,要用[]括起来。 c.update(b) # 也可以直接添加一个集合到别一个集合。 print(c) b.remove(7) #只能删除1项,指定删,没有会报错。 print(len(c)) #长度 print(c) print(‘wjy‘ in c) # 判断X是否是S的成员,返回布尔值 print(‘wjy‘not in c) # 判断X是否不是s的成员,字符串,列表,字典,集合都用同一种方法表示。 c.pop() # 任意删,由于集合无序,所以这里跟下标会报错。列表用这种方法可以删除对应下标的值。 print(c) print(c.discard(‘beiyou‘)) #指定删,没有不报错也不返回信息,打印结果为None.
打印结果:
{1, 2, 3, 4, 5, 6, 7, 9, ‘wjy‘} 9 {1, 2, 3, 4, 5, 6, 7, 9, ‘wjy‘} True False {2, 3, 4, 5, 6, 7, 9, ‘wjy‘} None
2、文件操作
python 运维自动化之路 Day3
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。