python基础教程之lambda表达式使用方法

WBOY
Release: 2016-06-16 08:45:18
Original
1586 people have browsed it

Python中,如果函数体是一个单独的return expression语句,开发者可以选择使用特殊的lambda表达式形式替换该函数:

复制代码 代码如下:

lambda parameters: expression

lambda表达式相当于函数体为单个return语句的普通函数的匿名函数。请注意,lambda语法并没有使用return关键字。开发者可以在任何可以使用函数引用的位置使用lambda表达式。在开发者想要使用一个简单函数作为参数或者返回值时,使用lambda表达式是很方便的。下面是使用lambda表达式作为内置filter函数的一个参数的示例:

复制代码 代码如下:

aList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
low = 3
high = 7
filter(lambda x, l=low, h=high: h>x>l, aList) # returns: [4, 5, 6]

作为另外一种选择,开发者还可以使用一个可以为函数变量命名的本地def语句。然后,开发者可以使用这个名称作为参数或返回值。下面是使用本地def语句的相同filter示例:

复制代码 代码如下:

aList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
low = 3
high = 7
def within_bounds(value, l=low, h=high):
return h>value>l filter(within_bounds, aList) #
returns: [4, 5, 6]

因为lambda表达式只是偶尔有用,许多Python用户更喜欢使用def, def要更通用些,如果开发者为函数选择了一个比较合理的名称,会让代码具有更好的可读性。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!