1.filter (function, sequence) returns a sequence (sequence) that includes all elements that return a value of true after all call function (item) in a given sequence ( If possible, the same type is returned). If the sequence (sequence) is a string(String) or a tuple (tuple), the return value must be the same type, otherwise it is always list. For example, the following programs can calculate partial primes:
def return and x% 3 ! = 0 ... >>> filter (F, Range (2)) [5, 7, 11, 13, 17, 19, 23]
2.map (function, sequence) invokes function (item) for each element and returns the return value in a linked list. For example, the following program computes the cube:
def return x*x*x ... >>> Map (cube, range (1, one)) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
You can pass in multiple sequences, and the function must have a corresponding number of arguments, which in turn will invoke the function with the corresponding elements on each sequence (if some sequences are shorter than others, use None instead). If None is passed as a function, the parameter is returned as an alternative. For example:
>>> seq = range (8)defreturn x+y ... >>>2, 4, 6, 8, 10, 12, 14]
3.reduce (function, sequence) returns a single value, which is constructed by calling function functions first with the first two elements of the sequence , and then invoking the return value and the third argument. Proceed in turn. For example, the following program calculates the sum of integers 1 to 10:
def return x+y ... >>> reduce (Add, range (1, one))55
If there is only one element in the sequence, it is returned, and if the sequence is empty, an exception is thrown.
You can pass in the third parameter as the initial value. If the sequence is empty, the initial value is returned, otherwise the function will first receive the initial value and the first element of the sequence, then the return value and the next element, and so on. For example:
def sum (seq): ... def return x+y ... return reduce (add, seq, 0) ... >>> sum (range (1, one))55>>> sum ([]) 0
Do not define sum ()as in the example: because the aggregate value is a common requirement, there is already a built-in sum (sequence) function, which is very useful.
Python Functional Programming Filter (), map (), reduce () ...