首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python内置函数filter,地图,reduce

2012-12-25 
python内置函数filter,map,reducePython list function build in three useful funtion(1):filter(funtion

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 Trueelse:    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 1x is None, y is 2x is None, y is 3x 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 0x is None, y is 1x is None, y is 2x is None, y is 3x is None, y is 4
?

?

热点排行