#匿名函数
def isodd(x):
return x%2
a=isodd(10)
print(a)
isodd = lambda x: x%2
#无参数
#func= lambda:3,14
#func()
#print(a)
myadd = lambda x,y:x+y
A=myadd(1,2)
print(A)
mysum= lambda x,y,*args:x+y+sum(args)
mysum(1,2,3,4,5)
dlist=[{'name':'sun','age':10},{'name':'li','age':13},{'name':'zhao','age':12}]
sorted(dlist,key=lambda item:item.get('age'))
#函数式编程
l=['1','2','3']
[int(val)for val in l]
r=map(int,l)
list(r)
r1= [90,80,40]
r2=[88,92,77]
r=map(lambda x,y:x+y,r1,r2)
print(list(r))
#消费统计
bill=['Apple 20','Pear 5','Banana 10']
r=map(lambda x:x.split()[-1],bill)
value = list(r)
print(value)
print(sum(map(int,value)))
#reduce
from functools import reduce
#1~10阶乘
reduce(lambda x,y:x*y,range(1,11))
#filter
#1.循环调用function
#2.保留被function处理的结果为True元素
#过滤偶数
l=[1,2,3,4,5,6]
list(filter(lambda x:x%2==0,l))
#过滤成绩
report=[[90,80],[50,70],[50,45]]
r=filter(lambda item:sum(item)/len(item) >=60,report)
print(list(r))
#闭包函数内部定义函数,内部函数使用外部变量,称之为闭包
def loginfo(msg,*args,**kwargs):
print('info:',msg)
def debug(msg,*args,**kwargs):
print('debug:',msg)
def logerror(msg,*args,**kwargs):
print('error:',msg)
def warning(msg,*args,**kwargs):
print('warning:',msg)
def logfunc():
level='info'
def logmsg(msg,*args,**kwargs):
print(f"{level}{msg}")
return logmsg
f=logfunc()
#函数当参数
def str2int(value):
print('in str2inf')
return int(value)
def pdeal(f):
def deal(value):
v = value.strip()
return f(v)
return deal
func=pdeal(str2int)
func('100')
#装饰器
def deco_fun(f):
print('call deco_func')
def foo(msg):
msg += '----->'
f(msg)
return foo
@deco_fun
def bar(msg): #bar=deco_func(bar) #bar, def bar(msg),bar= deco_func -> foo
print('call bar')
print(msg)
bar('text') #bar=deco_func(bar) #bar, def bar(msg),bar= deco_func -> foo
#递归函数
def func(value):
print('call func()')
value+=1
if value < 10:
func(value)
func(1)
def fun(num):
#参数
#截止条件
if num ==1:
#返回值
return 1
tmp = fun(num -1)
print(tmp,num)
return num * tmp
fun(5)
#遍历多维列表
# data = [1,2,3,[4,5,6,[7,8,9]]]
data=[1,2,3,['a','b','c'],['d','e','f']],[4,5,6,[7,8,9]]
# print(isinstance(data,list)) #判断是否是列表
def sortlist(l):
for value in l:
if isinstance(value,list):
sortlist(value)
else:
print(value,end=' ')
a=sortlist(data)
print(a)