Introduction to reduce and map in python
map(func,seq1[,seq2...])
: Acts the function func on each element of a given sequence and provides the return value with a list; if func is None, func behaves as an identity function, returning a list of n tuples containing the set of elements in each sequence.
reduce(func,seq[,init])
: func is a binary function that acts func on the elements of the seq sequence, carrying a pair at a time (the previous result as well as the next element of the sequence), successively acting the existing result and the next value on the subsequent result obtained, and finally reducing our sequence to a single return value: if the initial value init is given, the first comparison will be between init and the first sequence element instead of the not the first two elements of the sequence.
This article is mainly about python use reduce and map the string to digital, the following words do not say much, to see the detailed implementation of the method.
Exercise:
Write a str2float function using map and reduce to convert the string '123.456' to the floating point number 123.456
Solution and Idea Description:
from functools import reduce def str2float(s): s = ('.') # Split the string into two parts using the decimal point as a separator def f1(x,y): # Function 1, the number before the decimal point is handled with this function return x * 10 + y def f2(x,y): # Function 2, the number after the decimal point is handled by this function return x / 10 + y def str2num(str): # Function 3, used to change the string '123' into numbers one by one return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[str] return reduce(f1,map(str2num,s[0])) + reduce(f2,list(map(str2num,s[1]))[::-1])/10 # The last one is the essence of this solution # # For the number '123' before the decimal point, normal summation with x * 10 + y gives 123, how do you get 0.456 for the number '456' after the decimal point? #First turn the string '456' into a list [4,5,6] using list(map(str2num,s[1])) # Then take the list from back to front using [::-1] slicing, the list becomes [6,5,4] # Then put [6,5,4] into the f2 function using the reduce function to calculate, ( 6 / 10 + 5) / 10 + 4 = 4.56, resulting in 4.56 # Then divide by a 10, resulting in 0.456, which successfully turns the string '456' into the floating point number 0.456 #Add up the before and after results,That's the final solution.,Successfully put the string'123.456'Turned into a floating point number123.456
summarize
The above is the entire content of this article, I hope that the content of this article for everyone to learn or use python can bring some help, if there are questions you can leave a message to exchange.