`
qiaoqinqie
  • 浏览: 59193 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

python内置函数filter,map,reduce

阅读更多

Python list function build in three useful funtion

(1):filter(funtion,sequence)

This function will return the item in the sequence invoke the function and return true

such as:

def f(x):
if x > 0:
    return True
else:
    return False
 

filter(f,range(-3,4))

will return(1,2,3)

(2):map(function,sequence[,sequence...])

This funcion will map all the sequence one by one, so the sequence list's size must be all the same.

for example:

def m(x,y,z):
    return x+y+z
 

map(f,range(3),range(3),range(3))

will return

[0,3,6]

so, how many params the function has. how many sequence are needed

(3):reduce(function,sequence)returns a single value constructed by calling the binary function function on the first two items of the sequence, then on the result and the next item, and so on.

for example:

>>> def r(x,y):
    print 'x is %s, y is %s' % (x,y)
>>> reduce(r,range(5))
x is 0, y is 1
x is None, y is 2
x is None, y is 3
x is None, y is 4
 

 

 

So the function must take two params,

and there is a third param, use it to set the first param

for example:

>>> reduce(r,range(5),1)
x is 1, y is 0
x is None, y is 1
x is None, y is 2
x is None, y is 3
x is None, y is 4
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics