Python face question
Previous colleague asked a Python topic as follows, temporarily categorized as a face question
Title: Put similar‘123.456‘string into floating-point data
-
Method One:
print ‘{:.3f}‘.format(float(‘123.456‘)) >>> 123.456
-
Method Two: Specifying map , reduce higher order functions
Idea: The decimal point is processed first, and then the integer digits and decimal places are added. Steps are as follows
s = ‘123.456‘
-
Working with decimals: Use a string slice method.
s.split(‘.‘)
This gives you 2 an array of length[‘123‘, ‘456‘]
-
Processes the first element in the list (an integer column). Use an iterative approach to get integers123
def map_int(s): ‘‘‘ @see: 迭代时把字符串转换成int类型 ‘‘‘ return int(s)
Then use the higher map(func, seq) -order function to iterate over the string in the list: get[1, 2, 3]
map(map_int, s.split(‘.‘)[0])
-
Uses higher-order functions Reduce (func, seq) to accumulate data after map () 123
Reduce (lambda x, y: x*10 + y, map (map_int, S.split ('. ') [0]))
" > reduce (lambda x,y:x*10 + y, map (Map_int, S.split (". [0]))
The same method handles decimal digits
Reduce (lambda x, y: x*0.1 + y, map (map_int, S.split ('. ') [1] [::-1])) * 0.1
"> reduce (lambda x,y:x*0.1 + y, map (Map_int, S.split ( ") [1][::-< span class= "Hljs-number" >1])) * 0.1
-
The entire code block is as follows: or simply replace the Map_int () function with the following: Lambda X:int (x)
def Map_int(s): "@see: Convert a string to int type ' return int (s) reduce (lambda x,y:x*+ y) at iteration Map (Map_int, S.split ('. ') [0]) + reduce (lambda x,y:x*0.1 + y, map (Map_int, S.split ('. ') [1][::-1]) * 0.1
Generated by Haroopad
A python question previously asked by a colleague