Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字符串可以是分数,也可以是浮点数_Python_Floating Point_Fractions - Fatal编程技术网

Python字符串可以是分数,也可以是浮点数

Python字符串可以是分数,也可以是浮点数,python,floating-point,fractions,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.r

我有一个问题,我想取一个字符串,它可以表示一个分数,比如“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)
,并生成一个
分数
结果。例如:

>>> from fractions import Fraction
>>> float(Fraction('1/3'))
0.3333333333333333
>>> float(Fraction('2.0'))
2.0
由于可以将
分数
转换为
浮点
,因此您可以使用它无条件地生成
浮点
结果:

from fractions import Fraction

for line in f:
    content = line.strip('\r\n').split(" ")

    d1 = float(Fraction(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.
我冒昧地大大简化了您的代码
f.readlines()
已经返回了一个
列表
,因此再次迭代以填充
numberArray
是毫无意义的,而且由于您似乎只需要填充
numberArray
以迭代一次,因此直接迭代文件比创建两个无意义的临时文件更简单。如果您确实需要
列表
,只需执行以下操作:

numberArray = f.readlines()
for line in numberArray:

加载
列表
一次并直接存储,而不是一个元素一个元素地复制。

实际上这看起来很简单,我不知道为什么在问问题之前试图找到解决方案时找不到这一点。谢谢你的回答。这里根本不需要
re
。只需在str:中测试
if'/',而不是
is_frac=bool(重新搜索('/',str))
if is_frac: