Python has built in some very interesting but very useful functions, fully embodies the language charm of Python! [1] Filter (function, sequence)
Execute function (item) on item in sequence, and the item that executes the result of true is composed of a list/string/tuple (depending on the type of sequence) returned:
>>> def F(x): returnX%2!=0 andX%3!=0 >>>Filter (F, Range (2, -)) [5,7, One, -, -, +, at]>>> def F(x): returnX! =' A ' >>>Filter (F,"ABCdef")' Bcdef '
[2] Map (function, sequence)
Execute function (item) on item in sequence, and see the result of the execution to make a list return:
>>> def Cube(x): returnX*x*x>>>Map (cube, range (1, One)) [1,8, -, -, the,216,343, +,729, +]>>> def Cube(x) : returnx + X... >>>Map (Cube,"ABCDE") [' AA ',' BB ',' CC ',' DD ',' ee ']
In addition, the map supports multiple sequence, which requires that the function also supports the corresponding number of parameter inputs:
>>> def add(x, y):return>>> map(add, range(8), range(8)) [02468101214]
[3] Reduce (function, sequence, starting_value)
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:
>>> def add(x, y): returnX + y>>>Reduce (Add, range (1, One)) -Note1+2+3+4+5+6+7+8+9+Ten)>>>Reduce (Add, range (1, One), -) theNote1+2+3+4+5+6+7+8+9+Ten+ -)
[4] Lambda
This is a fun syntax for Python, which allows you to quickly define the smallest function of a single line, similar to a macro in C, these functions, called Lambda, are borrowed from Lisp and can be used wherever functions are needed:
>>> lambda2>>> g(36>>> (lambda2)(36
We can also use the filter map reduce and lambda together, the function can be simply written in one line.
filter(lambda kmpath: kmpath, string.strip(kmpath),string.split‘:‘)))
Looks like trouble, in fact, as in the language to describe the problem, very elegant.
Make a list of all the elements in L that are split with ': '. Each element of this list is made into a string strip, forming a list. Do a direct return operation on each element of this list (this place can be added to the filter limit) and eventually get a string that is ': ' In the split list, each string in the list is strip and can be filtered on a special string.
Python Special Syntax: filter, map, reduce, lambda