函数小高级 & lambda函数
------------------------------函数小高级------------------------------
1.1函数赋值
- 函数也相当于一个变量可以新定义一个变量用于接收函数
def funs():
return (1,2,3)
a = funs
print(a())
#与funs是等价的
- 同样也可以当做一个名称在列表中
def funs():
print (1,2,3)
a = funs
list_funs = [funs,funs,funs]
list_funs[1]()
#输出与funs()等价
- 同样也可以参与循环
def funs():
print (1,2,3)
a = funs
list_funs = [funs,funs,funs]
for item in list_funs:
v = item()
print(v)
'''
注意返回值None
输出的结果为
3
None
1 2 3
None
1 2 3
None
'''
- 放在字典中做字典的值也是可行的,虽然函数也可以做字典的键,但一般不这么做
def funs():
print (1,2,3)
def bars():
print(666)
info = {'k1':funs,'k2':bars}
info['k1']()
info['k2']()
- 函数名当做变量来使用
#练习1
def funs():
print(1,2,3)
list_funs = [funs(),funs()]
print(list_funs)
'''
输出结果呢为
1 2 3
1 2 3
[None, None]
'''
#练习2
def funs():
return(1,2,3)
list_funs = {'k1':funs,'k2':funs()}
print(list_funs)
'''
输出结果为
{'k1': <function funs at 0x030D87C0>, 'k2': (1, 2, 3)}
'''
#练习3
def funs(arg):
v1 = arg()
print(v1)
def show():
print(666)
result = funs(show)
print(result)
'''
输出结果为
666
None
None
'''
- 函数当做参数使用
#选择语音服务类
def funs():
print('语音服务')
def bars():
print('话费查询')
def bas():
print('流量服务')
def show():
print('游戏服务')
info = {'f1':funs,'f2':bars,'f3':bas,'f4':show}
choice = input('请选择所需服务:')
function_name = info.get(choice)
print(function_name)
if function_name:
function_name()
else:
print('输入错误')
------------------------lambda表达式--------------------------------
- lambda表达式:为了解决简单函数的情况,默认情况下会 return
- lambda表达式应用类型
func = lambda :100
func1 = lambda x1:x1*10
func2 = lambda *args,**kwargs:len(args) + len(kwargs)
- lambda表达式与三元运算混用,求两者的最大值
funs = lambda n1,n2 : n1 if n1 > n2 else n2
- 注意return的用法
USER_LIST = []
func1 = lambda x:USER_LIST.append(x) #此处由于修改列表不生成新的变量,所以此处没有返回值
v1 = func1('yang')
print(v1)
print(USER_LIST)
'''
结果为:
None
['yang']
'''
- 注意列表的返回值:列表的所有方法基本上所有return值为None
v1 = [1,2,3,4]
result = v1.append(2)
print(result)
print(v1)
'''
其结果为:
None
[1, 2, 3, 4, 2]
'''
- lambda表达式复杂化
funs = [lambda x:x.strip(), lambda y:y+99,lambda x,y:x+y]
记录学习的点点滴滴