Python开发——4.集合和字符串拼接
一、集合(set)
1.集合的特性:
不同元素组成、元素是无序排列的可hash值
2.集合转为列表
s1 = {11,"hechouzi",(11,22,33)}
names = list(s1)
print(names)
3.集合的方法
(1)add 添加元素
s = {11,22,(1,2),"hechouzi"}
s.add("kobe")
print(s)
(2) clear 清空元素
s = {11,22,(1,2),"hechouzi"}
s.clear()
print(s)
(3) copy
s = {11,22,(1,2),"hechouzi"}
s1 = s.copy()
print(s1)
(4)pop 随机删除,remove 指定删除,没有报错 discard 指定删除,没有不会报错
s = {11,22,(1,2),"hechouzi"}
s.pop()
s.remove(11)
s.discard(10)
print(s)
4.关系测试
(1)intersection(&)求取交集
s1 = {11,22,33,"hechouzi"}
s2 = {22,33,"kobe"}
# s3 = s1.intersection(s2)
s3 = s1 & s2
print(s3)
(2)union(|) 求取并集
s1 = {11,22,33,"hechouzi"}
s2 = {22,33,"kobe"}
# s3 = s1.union(s2)
s3 = s1 | s2
print(s3)
(3) difference(-)求取差集
s1 = {11,22,33,"hechouzi"}
s2 = {22,33,"kobe"}
# s3 = s1.difference(s2)
s3 = s1 - s2
print(s3)
(4)symmetric_difference(^)求取交叉补集
s1 = {11,22,33,"hechouzi"}
s2 = {22,33,"kobe"}
# s3 = s1.symmetric_difference(s2)
s3 = s1 ^ s2
print(s3)
(5) xx.update 将得到的集合更新到s1
s1.intersection_update(s2)
print(s1)
(6)isdisjoint 无交集返回True
s1 = {11,22,33,"hechouzi"}
s2 = {44,55}
v = s1.isdisjoint(s2)
(7)issubset s2是s1的子集返回True
s1 = {11,22,33,"hechouzi"}
s2 = {11,22}
v = s2.issubset(s1)
print(v)
(8)issuperset s1是s2的父集返回True
s1 = {11,22,33,"hechouzi"}
s2 = {11,22}
v = s1.issuperset(s2)
print(v)
(9) update 更新多个值
s1 = {11,"hechouzi",(11,22,33)}
s1.update((22,33))
print(s1)
二、字符串拼接
1.%
(1)%s 字符串类型,%d整型数字,%.2f 浮点数,小数点后2位默认6位,% .2f%%,百分比
s = "I am %s,I am %d, percent %.2f, %.2f%%"%("hechouzi",25,42.8888,24.88888)
print(s
(2)字典
s = "I am %(name)s,I am %(age)d"%{"name":"hechouzi","age":25}
print(s)
2.format
*列表 **字典
:b 二进制 :o 八进制 :d 整型 :x 十六进制小写 :X 十六进制大写
s = "i am {},age{},{}".format("bigmouse",25,"dazui")
print(s)
s = "i am {},age{},{}".format(*["bigmouse",25,"dazui"])
print(s)
s = "i am {0},age{1},{1}".format("bigmouse",25,"dazui")
print(s)
s = "i am {2},age{1},{0}".format(*["bigmouse",25,"dazui"])
print(s)
s = "i am {name},age{age},{name}".format(name="bigmouth",age=25)
print(s)
s = "i am {name},age{age},{name}".format(**{"name":"bigmouth","age":25})
print(s)
s = "i am {0[0]},age{0[1]},{1[2]}".format([1,2,3],[11,22,33])
print(s)
s = "i am {:s},age {:d},length {:.3f}".format("dazui",24,2.1111)
print(s)
s = "i am {name:s},age {age:d},{length:.3f}".format(name="dazui",age=24,length=2.1111)
print(s)
s = "i am {name:s},age {age:d},{length:.3f}".format(**{"name":"dazui","age":24,"length":2.1111})
print(s)
s1 = "num1:{:b} {:o} {:d} {:x} {:X} {:.3%}".format(24,24,24,24,24,24.888888,)
print(s1)
posted on 2018-04-24 21:42 hechengwei 阅读(604) 评论(0) 编辑 收藏 举报