Functional programming makes code simple and efficient.
Map function:
Map (func, *iterables), which is the function of mapping a list to another list.
class Map (object): """ Map (func, *iterables)--and map object make a iterator that computes the function using arguments from Each of the iterables. Stops when the shortest iterable is exhausted. """
View Code
How to use:
def f (x): return x**2= range (1,10= map (f,li)print(res)print (List (res)) """ <map Object at 0x000000000117e2e8>[1, 4, 9, (+), +, +, +, Bayi] """
Map (function, iterable, ...)
The map () function receives two parameters, one is a function, the other is an iterative object, and map functions the incoming function to each element of the sequence sequentially, returning a map object, not a list.
basically equivalent to [F (x) for x in interable], list derivation is more efficient than map
Map (Lambda x:x+1, Range (1, 3)) = = [x+1 for x in range (1,3)]
str = ["far","foo","bar" = map (lambda= List (MP)print(res)"" "[ ' Far ', ' FOO ', ' BAR '] "" "
View Code
Reduce function
Reduce (function, sequence[, initial]), which sequentially accumulates operations on an iterative object, such as adding or multiplying sequentially.
reduce()
Method receives a function as an accumulator (accumulator), and each value (from left to right) in the array begins to merge and eventually a value.
def # real signature unknown; restored from __doc__ """ Reduce (function, sequence[, initial]), value Apply a function of the arguments cumulatively to the items of a sequence, from left -to-right, so-to-reduce the sequence to a single value. For example, reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5]) calculates ((((( 1+2) +3) +4) +5). If Initial is present, it's placed before the items of the sequence in the calculation, and serves as a default when The sequence is empty. """
View Code
Direct use will be an error
Reduce (lambda x, y:x + y, [1, 3, 5, 7, 9])
"""
Nameerror:name ' reduce ' is not defined
"""
The correct use is: Reduce is a function in functools and needs to be referenced:from functools import reduce
How to use:
from Import = reduce (lambda x, Y:x*y, [1, 2, 3= reduce (lambda x, y:x + y, [1, 3, 5])
print
(res1)
print
(res2)
"" "" ""
Filter function
Filter (function or None, iterable), the function is to filter out some elements of the list according to the defined function
class Filter (object): """ Filter (function or None, iterable)--Filter Object Return an iterator yielding those items of iterable f or which function (item) is true. If function is None, and return the items is true. """
View Code
How to use:
Flt = filter (lambda x:x > 5,range = list (FLT)print(FLT)Print (res)"" "<filter object at 0x0000000000649a58>[6, 7, 8, 9] " ""
Python functional Programming Map-Reduce filter