我有一个问题,我想要一个字符串,可以说像'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) = ...
答案 0 :(得分:1)
我是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)
答案 1 :(得分:1)
The fractions.Fraction
constructor already knows how to parse both float
-like strings and fraction-like strings,并生成Fraction
个结果。例如:
>>> from fractions import Fraction
>>> float(Fraction('1/3'))
0.3333333333333333
>>> float(Fraction('2.0'))
2.0
由于Fraction
可以转换为float
,您可以使用它无条件地生成float
结果:
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()
已经返回list
,因此再次迭代它以填充numberArray
毫无意义,因为您似乎只填充numberArray
来迭代它一次无论如何,直接迭代文件比简单地制作两个毫无意义的临时文件更简单。如果你真的需要list
,你只需要:
numberArray = f.readlines()
for line in numberArray:
加载list
一次并直接存储,而不是逐个元素复制。