我想我会尝试编写一种测量单位转换的东西,只是为了练习。 我希望它能以一种方式工作,用户将得到一个单一的输入提示,它会根据字符串运行适当的功能。
我只是想知道什么是判断字符串格式如下的最佳方式:
数字单位
示例:30 cm inch(这将运行名为 cmtoinch 的函数,将数字 30 作为参数传递)。
我还需要能够分辨出哪个单位在另一个前面,因为“30 cm inch”会给出与“30 inch cm”不同的结果。
我想我应该将每个单元的名称放入一个列表中,但我不知道如何将字符串与列表进行比较以查看它是否至少包含两个值。
最佳答案
在字符串上使用 .split()
将其分解为单词(然后您可以将第一个重新解释为 int
或 float
视情况而定)。结果列表的顺序与输入字符串的顺序相同,因此您可以依次查看每个元素并对照您的单位引用列表进行检查。
为每个转换创建一个单独的函数可能不是您想要做的。相反,将输入转换为一些通用单元,然后从通用单元转换为所需的输出单元。为此,我们将每个单位与一个转换系数相关联;我们第一次乘法,第二次除法。
为了在单位名称和转换值之间建立关联,我们使用了一个dict
。这让我们可以通过插入名称直接查找转化值(value)。
conversion_rates = {
'in': 2.54, # 2.54 inches in a centimetre
'cm': 1.00, # this is our reference unit
'sun': 3.03 # a traditional Japanese unit of measurement
}
# raises ValueError if the number of words in the input is wrong
amount, original_unit, final_unit = line.split()
# raises ValueError if the amount is not formatted as a floating-point number
amount = float(amount)
# Now we do the conversion.
# raises KeyError if either unit is not found in the dict.
result = amount * conversion_rates[original_unit] / conversion_rates[final_unit]
关于Python,根据输入字符串的格式和内容运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4445521/