---map ()
First look at the map () function, the map function accepts two parameters, the first parameter is the algorithm, the second parameter is a specific value (note that the value must be iterative). That is, map (fun,iterable)
The map function calculates the specific value based on the algorithm and saves the result as an iterator. We know that iterators are ' lazy ' and only output one value at a time by invoking the next function.
Take a look at one of the simplest map () examples.
# Given a set of numbers 1,2,3,4,5,6. Requires that the value of each number plus one be calculated def fun (x): x =x+1 Span style= "color: #0000ff;" >return XLI =[1,2,3,4,5,6]r =< Span style= "color: #000000;" >map (Fun,li) print (Type (r)) Span style= "color: #0000ff;" >for i in print (i) # result: <class map >234567
Use map to assign multiple values to a row
X,y,z=map (Int,input ('Please input your number:'). Split ())print(x, Y, Z )
How do I capitalize the first letter of a name using map ()?
defDaxie (name):returnName[0].upper+name[1:]defdaxie2 (name):return '%s%s'% (Name[0].upper (), name[1:]) A=['Linghuchong','Dongfangbubai']r=map (daxie2,a) forIinchr:Print(i)
--reduce
Reduce, like the map function, accepts two parameters, but the reduce function calculates the result of the current value and the result of the next value in a cumulative way.
i.e.: Reduce (f,[1,2,3,4]) =f (f (3), 4)
Take a look at a simple example of the reduce function
# fromFunctoolsImportReducedefLeijia (x, y):#Note that the function we define must accept two parameters, otherwise it will be an error returnx+yPrint(Reduce (leijia,[1,2,3,4,5]))#Results15#of course, you can also add default parameters fromFunctoolsImportReducedefLeijia (x,y,z=2): returnx+y+ZPrint(Reduce (leijia,[1,2,3,4,5]))#Results:23
--filter
Same as two functions, accept two parameters, the first argument is the function name, the second argument is a sequence. However, the function returns the result (True/false) to determine whether the element is persisted, depending on the elements in the sequence that are acting on the function.
Consider a simple example of how to filter even numbers:
def Select (num): if num%2==0: return True Else: return falser=filter (select,[1,2,3,4,5,6]) for in R: Print (i)
--sorted
Sorted as the name implies, is the meaning of sorting.
>>> sorted ([22,33,55,11,44]) [11, 22, 33, 44, 55]
Sorted can also accept a key function to implement a custom sort
>>> sorted ([22,33,-11,44,-55],key=ABS) [-11, 22, 33, 44,-55]
The map/reduce/filter/sorted of Python basics