python lambda 用法

可以视lambda为一个简易的函数,它不需要return,形式简单

#冒号左边是变量

#冒号右边是返回值

例:

>>> def f (x): return x**2
... 
>>> print f(8)
64
 
>>> 
>>> g = lambda x: x**2
>>> 
>>> print g(8)
64
>>> 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

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

发布了46 篇原创文章 · 获赞 36 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/u011467621/article/details/47971921