2018-08-12



reduce的用法实例:

#!/usr/bin/env python3

... #-*-coding:utf-8-*-

...

>>> from functools import reduce

>>>

>>> CHAR_TO_INT = {

...    '0':0,

...    '1':1,

...    '2':2,

...    '3':3,

...    '4':4,

...    '5':5,

...    '6':6,

...    '7':7,

...    '8':8,

...    '9':9,

... }

>>>

>>> def str2int(s):

...    ints = map(lambda ch: CHAR_TO_INT[ch],s)

...    return reduce(lambda x,y:x *10 + y,ints)

...

>>> print(str2int('0'))

0

>>> print(str2int('12300'))

12300

>>> print(str2int('0012345'))

12345



CHAR_TO_FLOAT = {

...    '0':0,

...    '1':1,

...    '2':2,

...    '3':3,

...    '4':4,

...    '5':5,

...    '6':6,

...    '7':7,

...    '8':8,

...    '9':9,

...    '.':-1

... }

>>>

>>>

def str2float(s):

...    nums = map(lambda ch: CHAR_TO_FLOAT[ch],s)

...    point = 0

...    def to_float(f,n):

...        nonlocal point

...        if n == -1:

...            point = 1

...            return f

...        if point == 0:

...            return f * 10 + n

...        else:

...            point = point * 10

...            return f + n / point

...    return reduce(to_float,nums,0.0)

...

>>> print(str2float('0'))

0.0

>>> print(str2float('123.456'))

123.456

>>> print(str2float('123.45600'))

123.456

>>> print(str2float('0.1234'))

0.12340000000000001

>>> print(str2float('.1234'))

0.12340000000000001

>>> print(str2float('120.0034'))

120.0034

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Fourier series The first class math and engineering of re...
    快乐的大脚aaa阅读 1,404评论 0 0
  • 统计学习方法笔记(一) 1.1实现统计学习方法的步骤 1.得到一个有限的训练数据集。 2.确定包含所有可能的模型的...
    Neuromance_ea9a阅读 2,256评论 0 0
  • [echarts属性的设置(完整大全)]转自https://www.cnblogs.com/benmumu/p/8...
    雅雅的前端工作学习阅读 2,481评论 0 0
  • 体彩―――――― 303期胆3849.开458√ 304期胆3849.开444√ 305期胆0549.开005√ ...
    翅咤风云阅读 1,098评论 0 0
  • 场景1:田鼠在家开心地啃着大麦和谷子,过着无忧无虑的快乐生活。 场景2:家鼠刚刚吃完大餐,大腹便便躺在洞穴里,突然...
    混沌初期阿克曼阅读 7,057评论 0 0