集合
#集合中不存在重复元素,因此主要用来去重
s=set('hello')
print(s) #{'e', 'l', 'o', 'h'}
#添加
s.add('s')
#清空
s.clear()
print(s)
#浅拷贝
s1=s.copy()
s={'sb',1,2,3,4,5,6}
#随机删
s.pop()
#指定删除
s.remove('sb')
s.remove('hellol') #删除元素不存在会报错
s.discard('sbbbb')#删除元素不存在不会报错
print(s)
python_l=['lcg','szw','zjw','lcg']
linux_l=['lcg','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(p_s.difference(l_s))
print('差集',l_s-p_s)
print(l_s.difference(p_s))
#交叉补集
print('交叉补集',p_s.symmetric_difference(l_s))
print('交叉补集',p_s^l_s) #异或
# s1={1,2}
# s2={2,3,5}
# print(s1.isdisjoint(s2)) #没有交集返回True,否则返回False
# s1={1,2}
# s2={1,2,3}
# print(s1.issubset(s2))#s1 是s2 的子集
# print(s2.issubset(s1))#False
#
# print(s2.issuperset(s1))#s1 是s2 的父集
#
# 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' % ('ab','de')
print(msg)
tpl = "percent %.2f" % 99.976234444444444444
print(tpl)
tpl = 'percent %.2f %%' % 99.976234444444444444
print(tpl)
tpl = "i am %(name)s age %(age)d" % {"name": "abc", "age": 8}
print(tpl)
msg='i am %(name)+60s my hobby is alex' %{'name':'liu'}
print(msg)
print('root','x','0','0',sep=':')
函数参数
def test(x,y,z):
print(x)
print(y)
print(z)
test(1,2,3)
test(y=1,x=3,z=4)
test(1,y=2,3)
test(1,3,y=2)
test(1,3,z=2)
test(1,3,z=2,y=4)
test(z=2,1,3)
def test(x,*arg):
print(x)
print(arg)
test(1)
test(1,2,3,4,5)
test(1,{'name':'alex'})
test(1,['x','y','z'])
test(1,*['x','y','z'])
test(1,*('x','y','z'))
函数局部变量与全局变量
如果函数的内容无global关键字,
NAME = ["a","b"]
def qupengfei():
NAME = "c"
print('d', NAME)
qupengfei()
NAME = ["a","b"]
def qupengfei():
NAME.append('e')
print('c', NAME)
qupengfei()
如果函数的内容有global关键字
- 有声明局部变量
NAME = ["a","b"]
def qupengfei():
global NAME
NAME = "d"
print('c', NAME)
qupengfei()
NAME = ["a","b"]
def qupengfei():
NAME = "c"
global NAME
print('d', NAME)
qupengfei()
NAME = ["a","b"]
def qupengfei():
global NAME
NAME = ["a"]
NAME.append('e')
print('c', NAME)
qupengfei()
函数前向引用
def foo():
print('from foo')
bar()
foo()
def bar():
print('from bar')
def foo():
print('from foo')
bar()
def bar():
print('from bar')
foo()