之前同事问了一道 Python 题目如下,暂时归类为面试题
的字符串转换成浮点型数据
- '123.456'
- >>> print '{:.3f}'.format(float('123.456'))
- >>> 123.456
、
- map
高阶函数 思路:先处理小数点,然后在整数位、小数位相加。步骤如下
- reduce
- s = '123.456'
这样就得到长度为
- s.split('.')
的数组
- 2
- ['123', '456']
- 123
然后使用高阶函数
- def map_int(s):
- '''
- @see: 迭代时把字符串转换成int类型
- '''
- return int(s)
对 list 中的字符串迭代:得到
- map(func, seq)
- [1, 2, 3]
- map(map_int, s.split('.')[0])
,对
- reduce(func, seq)
后的数据累积得到
- map()
- 123
同样的方法处理小数位
- reduce(lambda x, y: x * 10 + y, map(map_int, s.split('.')[0]))
- reduce(lambda x, y: x * 0.1 + y, map(map_int, s.split('.')[1][: :-1])) * 0.1
- def map_int(s):
- '''
- @see: 迭代时把字符串转换成int类型
- '''
- return int(s)
- reduce(lambda x,y : x*10 + y, 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
来源: http://www.cnblogs.com/xiaozi-autotestman/p/7296596.html