如何找到表示为字符串和部分分数的两个数字的中点,例如。 “1 1/2 - 2”?

How do I find the midpoint of two numbers that are represented as a string and partial fraction eg. '1 1/2 - 2'?

l = ['1 1/2 - 2', '1 - 1 1/2', '1 1/4 - 2', '1 1/4 - 2', '1 - 11/2', '3 - 5', '1 1/4 - 2']

如何找到列表中每个范围的中点?例如第一个 '1 1/2 - 2' 应该是 1.75

让我们把它分成几个部分。对于列表中的每一项,我们必须将其分解为整数和小数部分,然后我们必须将两者都转换为小数。

不幸的是,fractions 模块中的混合数字支持在 Python 3 中已弃用,因此我们必须构建自己的。

from fractions import Fraction

def mixed_to_float(s):
    return sum(map(lambda i : float(Fraction(i)), s.split(' ')))

list = ['1 1/2 - 2', '1 - 1 1/2', '1 1/4 - 2', '1 1/4 - 2', '1 - 11/2', '3 - 5', '1 1/4 - 2']
for item in list:
    parts = map(lambda i : mixed_to_float(i), item.split(" - "))
    print (sum(parts)/2)