Python特殊語法:filter、map、reduce、lambdaPython內置了一些非常有趣但非常有用的函數,充分體現了Python的語言魅力! http://www.cnblogs.com/longdouhzt/archive/2012/05/19/2508844.html
[轉] http://hi.baidu.com/black/item/307001d18715fc322a35c747
---------------------------------------------------------------
lambda表達式返回一個函數對象
例子:
func = lambda x,y:x+y
func相當于下面這個函數
def func(x,y):
return x+y
注意def是語句而lambda是表達式
下面這種情況下就只能用lambda而不能用def
[(lambda x:x*x)(x) for x in range(1,11)]
map,reduce,filter中的function都可以用lambda表達式來生成!
map(function,sequence)
把sequence中的值當參數逐個傳給function,返回一個包含函數執行結果的list。
如果function有兩個參數,即map(function,sequence1,sequence2)。
例子:
求1*1,2*2,3*3,4*4
map(lambda x:x*x,range(1,5))
返回值是[1,4,9,16]
reduce(function,sequence)
function接收的參數個數只能為2
先把sequence中第一個值和第二個值當參數傳給function,再把function的返回值和第三個值當參數傳給
function,然后只返回一個結果。
例子:
求1到10的累加
reduce(lambda x,y:x+y,range(1,11))
返回值是55。
filter(function,sequence)
function的返回值只能是True或False
把sequence中的值逐個當參數傳給function,如果function(x)的返回值是True,就把x加到filter的返回值里面。一般來說filter的返回值是list,特殊情況如sequence是string或tuple,則返回值按照sequence的類型。
例子:
找出1到10之間的奇數
filter(lambda x:x%2!=0,range(1,11))
返回值
[1,3,5,7,9]
如果sequence是一個string
filter(lambda x:len(x)!=0,'hello')返回'hello'
filter(lambda x:len(x)==0,'hello')返回'' |
|