简体   繁体   English

在 Python 中将混合数转换为小数

[英]Converting Mix Numbers to Decimals in Python

I'm trying to write a program that converts three (3) measurements (eg 11 1/2", 12 3/8", 11 5/8") to decimal format then finds the average of the three (3) measurements. I already have code that finds the avg of three (3) measurements in decimal format. However, I can't seem to figure out how to first convert the mix number measurements into decimals...我正在尝试编写一个程序,将三 (3) 个测量值(例如 11 1/2"、12 3/8"、11 5/8")转换为十进制格式,然后找到三 (3) 个测量值的平均值。我已经有代码可以找到十进制格式的三 (3) 个测量值的平均值。但是,我似乎无法弄清楚如何首先将混合数测量值转换为小数...

num = int(input('How many numbers?: '))
total_sum = 0
for n in range(num):
    numbers = int(input('Enter number : '))
    total_sum += numbers
avg = total_sum/num
print('Average of ', num, ' numbers is :', avg)

You can use regex for this:您可以为此使用正则表达式:

import re
def mixed_to_decimal(mixed):
    match = re.fullmatch(r'(\d+)\s+(\d+)/(\d+)"?', mixed)
    if match is None:
        raise ValueError("Invalid mixed number.")
    a, b, c = map(int, match.groups())
    return a + b / c

mixed_to_decimal('11 1/2"') # 11.5
mixed_to_decimal('11 3') # ValueError
mixed_to_decimal('6 3/4') # 6.75

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM