Python has built-in special functions that are Python-specific. You can make your code more concise.
Examples can be seen:
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 ']
A function (item) is executed on item in sequence, and the item that executes the result of true consists of a list/string/tuple (depending on the type of sequence) returned.
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 ']
Execute function (item) on item in sequence, and see the result of the execution to make a list return:
Map also supports multiple sequence, which requires that the function also supports the corresponding number of parameter inputs:
def add (x, y): Return x+y
Print map (add, Range), 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)
The function is called on an iteration of the item order in sequence, and if there is starting_value, it can also be called as an initial value, for example to sum the 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 that Python supports, which allows you to quickly define the smallest function of a single line, similar to a macro in C, which are called lambda functions.
Python Special Syntax: filter, map, reduce, lambda