cencenhai 发表于 2017-5-3 06:59:32

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
  
  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
 
页: [1]
查看完整版本: python内置函数filter,map,reduce