一:前文回顾:
可变不可变
1.可变(修改里面的元素值,id不变):列表,字典
2.不可变:字符串,数字,元祖
访问顺序:
1.顺序访问:字符串,列表,元祖
2.映射:字典
3.直接访问:数字
存放元素个数:
1.容器类型:列表,元祖,字典
2.原子:数字,字符串
二:集合
1.概念
- 不同元素
- 一组无序排列元素
- 元素必须是不可变
2.创建
{1,2,3,4}或者定义集合
s = set('hello') print(s) s = set(['alex','alex','sb']) print(s) {'h', 'e', 'l', 'o'} {'sb', 'alex'}
3.集合功能函数
s ={1,2,3,4,5,}
s.add('alex')
s.clear()
s.copy()
s.pop()#随机删
s.remove()#指定元素删,若元素不存在则报错
s.discard()#指定元素删,若元素不存在不会报错
4.集合关系运算
#集合关系运算 python_l = ['lcd','szw','ghj'] linux_l = ['lcd','szw'] python_and_linux_l = [] for p_name in python_l: if p_name in linux_l: python_and_linux_l.append(p_name) print(python_and_linux_l) python_l = ['lcd','szw','ghj'] linux_l = ['lcd','szw','sb'] #求交集 p_s = set(python_l) l_s = set(linux_l) print(p_s,l_s) print(p_s.intersection(l_s)) print(p_s&l_s) #求并集 print(p_s.union(l_s)) print(p_s|l_s) #差集 print('差集',p_s-l_s) print('差集',l_s-p_s) print(p_s.difference(l_s)) #交叉补集 # print(p_s.symmetric_difference(l_s)) # print(p_s^l_s) #查看是否交集 print(p_s.isdisjoint(l_s)) #p_s是否是l_s的子集 print(p_s.issubset(l_s)) #l_s是否是p_s的父集 print(p_s.isuperset(l_s)) s1 ={1,2} s2 ={1,2,3} s1.update(s2)#更新多个值 s1.add(1,2,3,4) #更新一个值 s1.union(s2) print(s1) #集合是可变,变成不可变 s =frozenset('hello') print(s)
三.字符串格式化
msg ='i am %s my hobby is %s' % ('lhf','alex') print(msg) msg ='i am %s my hobby is %d' % ('lhf',3) print(msg)
#打印浮点位 tp1 ='percent %.3f' % 55.45678 print(tp1) #打印百分比 tp1 ='percent %.3f %%' % 55.45678 print(tp1) msg ='i am %(name)-60s my hobby is alex' %{'name':'lhf'} print(msg) #拼接 print('root','x','0','0',sep=':')
四.format 字符串格式化
#format字符串格式化 tp1 ='i am {2},age {1},{0}'.format('seven',18,'alex') print(tp1) tp1 ='i am {name},age {age},really {name}'.format(name='seven',age=18) print(tp1) tp1 ='i am {2},age {1},{0}'.format(*['seven',18,'alex'])#用列表传必须用* print(tp1) tp1 ='i am {name},age {age},really{name}'.format(**{'name':'seven','age':18})#用字典传必须用** print(tp1) tp1 ='i am {0[0]},age{0[1]},really{1[2]}'.format([1,2,3],[11,22,33]) print(tp1) tp1 ='i am {:s},age{:d},really{:f}'.format('seven',18,88.8876) print(tp1) tp1 ='i am {:s},age{:d}'.format(*['seven',18]) print(tp1) tp1 ='i am {name:s},age{age:d}'.format(name='seven',age=18) print(tp1) tp1 ='i am {name:s},age{age:d}'.format(**{'name':'seven','age':18}) print(tp1)