Python: Lambda Functions

1. 作用

快速创建匿名单行最小函数,对数据进行简单处理, 常常与 map(), reduce(), filter() 联合使用。

2. 与一般函数的不同

>>> def f (x): return x**2
...
>>> print f(8)
64
>>>
>>> g = lambda x: x**2 # 匿名函数默认冒号前面为参数(多个参数用逗号分开), return 冒号后面的表达式
>>>
>>> print g(8)
64

3. 与一般函数嵌套使用

与一般函数嵌套,可以产生多个功能类似的的函数。

>>> def make_incrementor (n): return lambda x: x + n
>>>
>>> f = make_incrementor(2)
>>> g = make_incrementor(6)
>>>
>>> print f(42), g(42)
44 48
>>>
>>> print make_incrementor(22)(33)
55

4. 在 sequence 中的使用

filter(function or None, sequence) -> list, tuple, or string

map(function, sequence[, sequence, ...]) -> list

reduce(function, sequence[, initial]) -> value

>>> 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) # return (((((a+b)+c)+d)+e)+f) equal to sum()
139

5. 两个例子

a) 求素数

>>> nums = range(2, 50)
>>> for i in range(2, 8):
... nums = filter(lambda x: x == i or x % i, nums)
...
>>> print nums
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

注释: "Leave the element in the list if it is equal to i, or if it leaves a non-zero remainder when divided by i. Otherwise remove it from the list." 从 2 到 7 循环,每次把倍数移除。

 

b) 求单词长度

>>> sentence = 'It is raining cats and dogs'
>>> words = sentence.split()
>>> print words
['It', 'is', 'raining', 'cats', 'and', 'dogs']
>>>
>>> lengths = map(lambda word: len(word), words)
>>> print lengths
[2, 2, 7, 4, 3, 4]

 

 



参考资料:

http://www.secnetix.de/olli/Python/lambda_functions.hawk

 

 

posted on 2013-07-06 18:51  daniel-D  阅读(1177)  评论(0编辑  收藏  举报

导航