代码之家  ›  专栏  ›  技术社区  ›  mpen

把分数转换成浮点数?

  •  19
  • mpen  · 技术社区  · 15 年前

    有点 like this question 但反过来。

    给了一个类似的字符串 1 , 1/2 1 2/3 ,将其转换为浮点的最佳方法是什么?我正在考虑逐个使用regex,但也许有人知道更好的方法,或者预先存在的解决方案。我希望我能用 eval 但是我认为第三个案例阻止了这一点。

    9 回复  |  直到 10 年前
        1
  •  33
  •   newacct    15 年前

    可能是这样的(2.6+)

    from fractions import Fraction
    float(sum(Fraction(s) for s in '1 2/3'.split()))
    
        2
  •  6
  •   Dave    15 年前

    尽管你应该完全远离埃瓦尔。也许是更精致的版本:

    num,den = s.split( '/' )
    wh, num = num.split()
    result = wh + (float(num)/float(den))
    

    抱歉,应该是num.split而不是s.split和casts。编辑。

        3
  •  6
  •   Community CDub    8 年前

    我调整了一下 James' answer 一点。

    def convert_to_float(frac_str):
        try:
            return float(frac_str)
        except ValueError:
            num, denom = frac_str.split('/')
            try:
                leading, num = num.split(' ')
                whole = float(leading)
            except ValueError:
                whole = 0
            frac = float(num) / float(denom)
            return whole - frac if whole < 0 else whole + frac
    
    
    print convert_to_float('3') # 3.0
    print convert_to_float('3/2') # 1.5
    print convert_to_float('1 1/2') # 1.5
    print convert_to_float('-1 1/2') # -1.5
    

    http://ideone.com/ItifKv

        4
  •  3
  •   James Errico    11 年前

    我知道这里已经有好几个好答案了,但我很幸运。它还具有这样的好处:如果您要分析混合的数据集,它将允许使用非小数字符串,因此不需要检查它是小数字符串还是非前置字符串。

    def convert_to_float(frac_str):
        try:
            return float(frac_str)
        except ValueError:
            try:
                num, denom = frac_str.split('/')
            except ValueError:
                return None
            try:
                leading, num = num.split(' ')
            except ValueError:
                return float(num) / float(denom)        
            if float(leading) < 0:
                sign_mult = -1
            else:
                sign_mult = 1
            return float(leading) + sign_mult * (float(num) / float(denom))
    

    >>> convert_to_float('3')
    3.0
    >>> convert_to_float('1/4')
    0.25
    >>> convert_to_float('1 2/3')
    1.6666666666666665
    >>> convert_to_float('-2/3')
    -0.6666666666666666
    >>> convert_to_float('-3 1/2')
    -3.5
    
        5
  •  2
  •   schnaader    15 年前

    这可能是一个肮脏的解决方案,但您可以将空间转换为 + 签署解决第三个案件(或 - 如果分数为负)。

        6
  •  2
  •   nvd    11 年前
    def fractionToFloat(fraction):
    
        num = 0
        mult = 1
    
        if fraction[:1] == "-":
            fraction = fraction[1:]     
            mult = -1
    
        if " " in fraction:
            a = fraction.split(" ")
            num = float(a[0])
            toSplit = a[1]
        else:
            toSplit = fraction
    
        frac = toSplit.split("/")
        num += float(frac[0]) / float(frac[1])
    
        return num * mult
    

    它还可以处理“2 1/1e-8”、“-1/3”和“1/5e3”。

        7
  •  1
  •   Laurence Gonsalves    15 年前

    此实现避免了使用eval,并在2.6之前版本的python上工作。

    # matches a string consting of an integer followed by either a divisor
    # ("/" and an integer) or some spaces and a simple fraction (two integers
    # separated by "/")
    FRACTION_REGEX = re.compile(r'^(\d+)(?:(?:\s+(\d+))?/(\d+))?$')
    
    def parse(x):
      i, n, d = FRACTION_REGEX.match(x).groups()
      if d is None: return i  # if d is None, then n is also None
      if n is None: i, n = 0, i
      return float(i) + float(n) / float(d)
    

    测试:

    >>> for x in ['1', '1/2', '1 2/3']: print parse(x)
    ... 
    1
    0.5
    1.66666666667
    
        8
  •  0
  •   Alex Martelli    15 年前

    根据要支持分数的语法, eval('+'.join(s.split())) (有真正的划分——即python 3或 from __future__ import division 在Python2中——可能有效。它将涵盖你提到的所有案例,尤其是。

        9
  •  0
  •   ghostdog74    15 年前
    >>> s="1/2"
    >>> eval('/'.join(map(str,map(float,s.split("/")))))
    0.5
    
    >>> s="3/5"
    >>> eval('/'.join(map(str,map(float,s.split("/")))))
    0.59999999999999998
    
    推荐文章