[英]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'] 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']
How do I find the midpoint for each of ranges in the list?如何找到列表中每个范围的中点? For example the first one '1 1/2 - 2' should be 1.75例如第一个 '1 1/2 - 2' 应该是 1.75
Let's break this into a few parts.让我们把它分成几个部分。 For each of the items in the list, we'll have to break it into its integer and fractional component, and then we'll have to convert both to decimals.对于列表中的每个项目,我们必须将其分解为 integer 和小数部分,然后我们必须将两者都转换为小数。
Unfortunately, mixed number support in the fractions
module was deprecated in Python 3, so we'll have to build our own.不幸的是, 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.