我有一个问题,我想获取一个字符串,该字符串可以表示“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/