Python字符串要么分数要么浮点到 float

标签 python floating-point fractions

我有一个问题,我想获取一个字符串,该字符串可以表示“1/6”之类的分数或浮点“2.0”,并将它们都计算为最终浮点值。我不知道如何处理这两种情况出现的可能性,或者如何处理它们,以便获得分数的浮点输出。

numberArray = []
d1 = 0
d2 = 0

fileInput = f.readlines()

for line in fileInput:
    numberArray.append(line)

for i in numberArray:
    content = i.replace("\n","").split(" ")

    d1 = (float(content[0]))
    //The rest of data in the line is stored below (d2, d3 etc), but this isn't 
    // important. The important part is the first item that comes up in each line, 
    //and whether or not it is a fraction or already a float.

输入:

1/3 ...(rest of the line, not important)
2.0 ...

输出:

d1 (line1, item1) = 0.33
d2 (line1, item2) = ...

d1 (line2, item1) = 2.0
d2 (line2, item2) = ...

最佳答案

我是 python 新手,所以这可能不是最优雅的解决方案,但可能是这样的:

import re

values = ["3.444", "3", "1/3", "1/5"]

def to_float(str):
    is_frac = bool(re.search("/", str))
    if is_frac:
        num_den = str.split("/")
        return float(num_den[0]) / float(num_den[1])
    else:
        return float(str)

floats = [to_float(i) for i in values]
print(floats)

关于Python字符串要么分数要么浮点到 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50615330/

相关文章:

c++ - 找到等于实数分数的自然数分数

python - 如何通过时间累积每个 ID 的唯一行值的数量

python - Python 读取和写入 csv 文件

Python: Selenium with PhantomJS 空页面源码

python - 为什么使用多线程求和是正确的?

c - 如何从文件中读取未知数量的 float ?

更新后 Ruby Float#round 行为发生变化

javascript - 如何使用dojo.number.round实现整数的toFixed功能?

python - 仅在重复 python 时四舍五入到小数点后两位

c# - 有分数乘法的标准方法吗?