python第五天---集合与format格式化

时间:2022-05-31 06:01:33
"""
集合:set
1、由不同元素组成,
2、无序
3、不可变:数字、字符串、元组
不可变类型
"""
s = {1, 2, 3, 4, 1, 6, 3, 4, 5, 6}
print(s)

t = {'hello', 'ssad', 'asd', 'asd', 'hello'}
print(t)

s1 = set('hello')
print(s1)

# s2 = set(['cui', 'hai', 'cheng', 'cui'])
# print('s2:', s2)

ss = {1, 2, 3, 4, 5, 6}

ss.add('3')  # 添加元素,只能一个值
ss.add(32)
print(ss)

# ss.clear()                # 清空集合
# print(ss)

s3 = ss.copy()
print(s3)

ss.pop()  # 随机删除
print(ss)
# ss.remove('3')              # 指定元素删除,不存在会报错
print(ss)

ss.discard('ewrewrewr')  # 删除元素不存在,不会报错
print(ss)

python_l = ['cui', 'hai', 'cheng', 'pipi', 'anan']
linux_l = ['cui', 'pipi', 'cheng', 'kele', 'honr']

p_l = set(python_l)
l_l = set(linux_l)

print(p_l, l_l)
print(p_l.intersection(l_l))  # 求p_l中和l_l一样的元素
print(p_l & l_l)  # 求p_l和l_l交集

print(p_l.union(l_l))  # 求p_l和l_l一共的元素
print(p_l | l_l)  # 求p_l和l_l并集

print("差集:", p_l - l_l)  # 求差集
print('chaji:', l_l - p_l)
print(p_l.difference(l_l))

print(p_l.symmetric_difference(l_l))  # 交叉补集
print(p_l ^ l_l)

s4 = {1, 2}
s5 = {3, 4}
print(s4.isdisjoint(s5))  # 没有交集的时候返回True

s6 = {1, 2, 3}
s7 = {1, 2}
print(s7.issubset(s6))  # s7是s6的子集

print(s6.issuperset(s7))  # s6是s7的父集

s7.update(s6)  # 更新多个值
print(s7)

# 集合变为不可变的
s9 = frozenset('hello')
print(s9)

s8 = ['pipi', 'cui', 'pipi', 'cui', 'cheng']
names = list(set(s8))
print(names)

"""
字符串格式化
%s 字符串,万能接
%d 整形数字
%f 浮点数(保存六位)  %.2f 保留两位
字典形式
"""
print('I am %s ,my hobby is %s' % ('cui', 'read book'))
print('I am is %d' % 20)
print('my percent is %.2f %%' % 98.44444)
print('I am %(name)s age %(age)d' % {'name': 'cui', 'age': 20})



"""
format 格式化
"""

tpl = "i am {}, age {}, {}".format("seven", 18, 'alex') print(tpl) tp2 = "i am {}, age {}, {}".format(*["seven", 18, 'alex']) print(tp2) tp3 = "i am {0}, age {1}, really {0}".format("seven", 18) print(tp3) tp4 = "i am {0}, age {1}, really {0}".format(*["seven", 18]) print(tp4) tp5 = "i am {name}, age {age}, really {name}".format(name="seven", age=18) print(tp5) tp6 = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18}) print(tp6) tp7 = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33]) print(tp7) tp8 = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1) print(tp8) tp9 = "i am {:s}, age {:d}".format(*["seven", 18]) print(tp9) tpl0 = "i am {name:s}, age {age:d}".format(name="seven", age=18) print(tpl0) tpl1 = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18}) print(tpl1) tpl2 = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) print(tpl2) tpl3 = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) print(tpl3) tpl4 = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15) print(tpl4) tpl5 = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15) print(tpl5)