最後更新: 2020-12-11
介紹
lambda: anonymous function <= 用完即丟的 Function
Syntax
lambda param1, param2, ... : expression
# 等於
def fun(param1, param2, ...): return expression fun(param1, param2, ...)
Exampe
<1>
def f (x): return x**2
f(3)
g = lambda x: x**2
<2>
my_list = [1, 2, 3]
map( lambda i: i * i, my_list )
====
foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27]
print map(lambda x: x * 2 + 10, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]
print reduce(lambda x, y: x + y, foo)
139
<3> reduce()
The function is called with the first two elements from the list,
then with the result of that call and the third element, and so on, until all of the list elements have been handled.