您的位置:首页 > 其它

匿名函数lambda

2015-06-20 22:04 357 查看
lambda x: x % 3 == 0

Is the same as
def by_three(x):
return x % 3 == 0

Only we don't need to actually give the function a name; it does its work and returns a value without one. That's why the function the lambda creates is an anonymous function.
当不需要给一个函数名字时多用lambda
When we pass the lambda to
filter
,
filter
uses
the lambda to determine what to filter, and the second argument (
my_list
, which
is just the numbers 0 – 15) is the list it does the filtering on.

my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)

结果
[0, 3, 6, 9, 12, 15]

Lambda functions are defined using the following syntax:
my_list = range(16)
filter(lambda x: x % 3 == 0, my_list)

Lambdas are useful when you need a quick function to do some work for you.
If you plan on creating a function you'll use over and over, you're better off using
def
and giving that function a name.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: