Python3 匿名函数

一 匿名函数

lambda函数也叫匿名函数,语法结构如下:

lambda x:x+1
x --> 形参
x+1 --> 返回值,相当于return x+1

实例(Python3.0+):

def foo(x):
	return x+1
print(foo(1))		

运行结果:
>>> 2

# 使用lambda函数替换如上函数:
lambda x:x+1
f = lambda x:x+1
print(f(1))

运行结果:
>>> 2    

例题:把字符串"sunwuk"变成'sunwuk_xiyouji'

def change_name(name):
    return name + "_xiyouji"
print(change_name("sunwuk"))

运行结果:
>>> sunwuk_xiyouji

----------
使用lambda函数方法:
f = lambda x:x+"_xiyouji"
print(f('sunwuk'))    

运行结果:
>>> sunwuk_xiyouji

以下是我复制过来的一些代码,正是通过这些代码让我对匿名函数有了一个比较深入的了解,很感谢不知名的作者。 

无参数匿名函数

实例(Python3.0+):

f = lambda :True
print(f())

运行结果
>>> True

等价于如下函数
def f():
  reture True
print(f())

运行结果
>>> True

字符串正常输出

实例(Python3.0+):

s = 'this is
a	test'
print(s)
print(s.split())  # split函数默认分割:空格,换行符,TAB键
print(' '.join(s.split()))

运行结果:
>>> this is
>>> a	test
>>> ['this', 'is', 'a', 'test']
>>> this is a test

用join函数把列表转换成字符串
f = lambda :' '.join(s.split())
print(f())
或
print((lambda s:' '.join(s.split()))('this is
a	test'))

运行结果:
>>> this is a test

"""
print((lambda x:x+1)(12))
相当于把12作为形参传入lambda函数中
"""

带参数匿名函数

实例(Python3.0+):

# lambda x: x**3 一个参数
print((lambda x:x**3)(2))

运行结果
>>> 8

# lambda x,y,z:(x+y+z) 多个参数
print((lambda x,y,z:(x+y+z))(1,2,3))

运行结果:
>>> 6

# lambda x,y=3:(x*y)  允许参数存在默认值
print((lambda x,y=2:(x+y))(2))

运行结果:
>>> 4

匿名函数调用  

实例(Python3.0+):

#直接赋值给一个变量,然后再像一般函数调用
f = lambda x,y,z:(x*y*z)
print(f(2,3,4))

# 返回一个元祖
a = lambda *z:z   
print(a('Testing1','Testing2'))
			
运行结果:
>>> ('Testing1', 'Testing2')

上例中相当于使用了函数的不定长参数*args,返回值为元组
def foo(*args):
print(args)

foo("zhubj","sunwk",'sas')

运行结果:
>>> ('zhubj', 'sunwk', 'sas')

#返回一个字典
c = lambda **arg:arg    
print(c(a=1,b=2))

运行结果:
>>> {'a': 1, 'b': 2}

上例中相对于使用了函数的**kwargs参数,返回值为字典
def foo(x,**kwargs):
print(x)
print(kwargs)

foo(1,a=2,b=3)

运行结果:
>>> 1
>>> {'a': 2, 'b': 3}

#直接后面传递实参
print((lambda x,y:x if x > y else y)(1,2))

运行结果:
>>> 2

  

原文地址:https://www.cnblogs.com/lvcm/p/9254809.html