一、三元表达式
def max2(x,y):
if x > y:
return x
else:
return y
res=max2(10,20)
x=10
y=20
# res=x if x > y else y
# print(res)
res='OK' if False else 'No'
print(res)
二、生成式
1、列表生成式
l=[]
for i in range(10):
if i > 4:
l.append(i**2)
l=[i**2 for i in range(10) if i > 4]
print(l)
names=['egon','alex_sb','kevin_sb','hxx_sb','cxx_sb']
sbs=[]
for name in names:
if name.endswith('sb'):
sbs.append(name)
sbs=[name.upper() for name in names if name.endswith('sb')]
print([name.upper() for name in names])
print([name for name in names if name.endswith('sb')])
2、字典表达式
res={i:i**2 for i in range(10) if i > 3}
print(res)
print({i for i in 'hello'})
3、生成器表达式
g=(i for i in rang(10) if i > 5)
print(g)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
with open('a.txt',mode='rt',encoding='utf-8')as f:
#print(len(f.read()))
#g=(len(line) for line in f)
#res=sum(g)
rer=sum(len(line) for line in f)
print(res)
三、匿名函数
def func():
print('from func')
func()
func()
func()
匿名函数就是只定义了一个函数的内存地址,主要用于临时使用一次的场景
func=lambda x,y:x+y
print(func)
print(func(1,2))
res=(lambda x,y:x+y)(1,2)
print(res)
print(max([10,11,-3,23]))
salaries={
'egon':3000,
'alex':100000000,
'wupeiqi':10000,
'yuanhao':2000
}
def func(k):
return salaries[k]
print(max(salaries,key=lambda k:salaries[k]))
print(min(salaries,key=func))
for循环的结果 比较依据
'egon' 3000
'alex' 100000000
'wupeiqi' 10000
'yuanhao' 2000
l=[4,2,3]
l_new=sorted(l,reverse=True)
print(l_new)
print(sorted(salaries,key=lambda k:salaries[k],reverse=True))