简体   繁体   English

如何找到表示为字符串和部分分数的两个数字的中点,例如。 '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'] 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.

相关问题 如何在python中的代码点上拆分unicode字符串? (例如\\ u00B7或\\ u2022)? - How do I split a unicode string on code points in python? (eg. \u00B7 or \u2022)? 我想找出两个分数之间的差异 - I want to find the difference between two fraction numbers 你如何使用字符串操作在python中创建一个由x框组成的X? (例如,替换,计数,查找,len等) - How do you create a n by n box of X's in python using string manipulation? (eg. replace, count, find, len, etc.) 如何通过Python Script Mac在另一个应用程序中打开文档(例如.txt) - How do I open a document (eg. .txt) in another app from a Python Script mac 用if语句连接字符串例如:if 5“> 4”: - Concatenate string with if statement eg.: if 5 “> 4”: 我应该如何在Python中包装一个交互式子进程(例如shell) - How should I wrap an interactive subprocess (eg. shell) in Python 如何通过部分字符串匹配合并两个数据帧? - How do I merge two dataframes by partial string match? 如何使递归 function 生成数字组合,例如。 对于 n=3、(1,1,1)、(1,1,2) 等等? - How to make a recursive function to generate the combination of numbers eg. for n=3, (1,1,1),(1,1,2) and so on? 如何在pygame中找到三角形的中点,然后递归地重复执行它以制作sierpinski三角形? - How do I find the midpoint of a triangle in pygame and then recursively execute it repeatedley to make a sierpinski triangle? 为什么在输入为小数的int(input())调用int(input())时会出现错误? - Why do I get an error when I call int(input()) where input is decimal (eg. '87.94')?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM