Python has some built-in special functions, which are very python-specific. Can make the code more concise.
You can see the example:
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']
Execute function(item) on the items in sequence one by one , the items whose execution result is True are composed into a List/String/Tuple (depending on the type of sequence) and returned.
can be regarded 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']
Execute function(item) on the items in sequence one by one ), see the execution results form a List and return:
map also supports multiple sequences, which requires the function to also support 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 (Note: 1 +2+...+99)
## 4970 (Note: 1+2+...+99+20)
Iteratively calls the function on the items in the sequence. If there is a starting_value, it can also be used as the initial value. Call, for example, can be used to sum a List:
4 lambda:
g = lambda s: s + ".fsh"
print g("haha")
print (lambda x: x * 2) ( 3)
## haha.fsh
## 6
This is an interesting syntax supported by Python, which allows you to quickly define a single-line minimal function, similar to macros in C language, these functions are called lambda.