您的位置:首页 > 编程语言 > Python开发

4.6 匿名函数:Lambda表达式

2014-02-14 00:38 295 查看
4.6 匿名函数:Lambda表达式

--Lambda函数是一种快速定义单行的最小函数,是从Lisp借用来的,可以用在任何需要函数的地方。

无须定义函数名称

写法举例

g = lambda x,y,z....:x*y

lambda 构造的是一个函数对象
example4.6.1

>>> g = lambda x,y:x*y
>>> g(520,520)
270400
example4.6.2

reduce为逐次操作list里的每项,接收的参数为2个,最后返回的为一个结果
注:win下Python3.3.3 未执行成功的案例(含reduce)

>>> z = range(1,6)
>>> z
range(1, 6)
>>> def f(x,y):
return(x*y)

>>> reduce(f,z)
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
reduce(f,z)
NameError: name 'reduce' is not defined
>>> ###lambda 函数的实现方法
>>> f = lambda x,y:x*y
>>> reduce(f,z)
Traceback (most recent call last):
File "<pyshell#71>", line 1, in <module>
reduce(f,z)
NameError: name 'reduce' is not defined
>>> reduce(lambda x,y:x*y ,l)
Traceback (most recent call last):
File "<pyshell#72>", line 1, in <module>
reduce(lambda x,y:x*y ,l)
NameError: name 'reduce' is not defined
注:学习内容来源于网易云课堂《疯狂的Python:快速入门精讲》;代码执行环境为Win;Python版本为 3.3.3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息