In this paper, from http://www.cnblogs.com/fangshenghui/p/3445469.html
Python Built in some special functions , These functions are very python characteristic . Can make the code more concise .
You can see examples :
1 filter(function, sequence):
str = ['a', 'b','c', 'd']
def fun1(s): return s if s != 'a' else None
ret = filter(fun1, str)
print ret
## ['b', 'c', 'd']
Yes sequence Medium item Execute sequentially function(item), The result of execution is True Of item Form a List/String/Tuple( Depending on sequence The type of ) return .
It can be seen as a filter function .
2 map(function, sequence)
str = ['a', 'b','c', 'd']
def fun2(s): return s + ".txt"
ret = map(fun2, str)
print ret
## ['a.txt', 'b.txt', 'c.txt', 'd.txt']
Yes sequence Medium item Execute sequentially function(item), See the implementation results to form a List return :
map Support multiple sequence, This requires that function It also supports a corresponding number of parameter inputs :
def add(x, y): return x+y
print map(add, range(10), range(10))
##[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
3 reduce(function, sequence, starting_value):def add1(x,y): return x + y
print reduce(add1, range(1, 100))
print reduce(add1, range(1, 100), 20)
## 4950 ( notes :1+2+...+99)
## 4970 ( notes :1+2+...+99+20)
Yes sequence Medium item Sequential iteration call function, If there is starting_value, It can also be called as an initial value , For example, it can be used to List Sum up :
4 lambda:
g = lambda s: s + ".fsh"
print g("haha")
print (lambda x: x * 2) (3)
## haha.fsh
## 6
This is a Python Support an interesting grammar , It allows you to quickly define the minimum function of a single line , Similar to C Macro in language , These are called lambda Function of .