Python,根据输入字符串的格式和内容运行函数
我想我应该尝试编写一种测量单位转换的东西只是为了练习。 我希望它的工作方式是向用户提供单个输入提示,并根据字符串运行适当的函数。
我只是想知道告诉天气的最好方法是什么,字符串的格式如下:
数字单位
示例:30厘米英寸(这将运行名为的函数cmtoinch 传递数字 30 作为参数)。
我还需要能够区分哪个单位在另一个单位前面,因为“30 厘米英寸”会给出与“30 英寸厘米”不同的结果。
我想将每个单元的名称放入一个列表中,但我不知道如何将字符串与列表进行比较以查看它是否至少包含两个值。
I thought I'd try writing a kind of a measurements units conversion thingy just for practice.
I would like it to work in a way that the user would be given a single input prompt and it would run the appropriate function based on the string.
I'm just wondering what would be the best way to tell weather the string is formatted like this:
number unit unit
example: 30 cm inch (this would run the function named cmtoinch passing the number 30 as an arguement).
I would also need to be able to tell which unit is in front of the other cause "30 cm inch" would give different results then "30 inch cm".
I was thinking I'd put the names of each unit into a list, but I don't know how to compare a string to the list to see if it contains at least two of the values.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在字符串上使用
.split()
将其分解为单词(然后您可以将第一个单词重新解释为int
或float
为合适的)。生成的列表将与输入字符串的顺序相同,因此您可以依次查看每个元素并根据单位参考列表进行检查。为每个转换创建一个单独的函数可能不是您想要做的。相反,将输入转换为某种通用单位,然后从通用单位转换为所需的输出单位。为此,我们将每个单位与一个转换因子相关联;我们第一次乘法,第二次除法。
为了在单位名称和转换值之间建立关联,我们使用
dict
。这让我们可以通过插入名称直接查找转换值。Use
.split()
on the string to break it into words (then you can re-interpret the first one as anint
orfloat
as appropriate). The resulting list will be in the same order as the input string, so you can look at each element in turn and check it against your reference list of units.Making a separate function for each conversion is probably not what you want to do. Instead, translate the input into some common unit, and then translate from the common unit to the desired output unit. To do this, we associate each unit with a single conversion factor; we multiply the first time, and divide the second time.
To make the association between unit names and conversion values, we use a
dict
. This lets us look up the conversion value directly by plugging in the name.根据此代码的组织,您可能需要使用
globals()
、.__dict__
或getattr(obj)
这里。我的示例使用globals()
。Depending on the organization of this code, you may want to use
globals()
,<modulename>.__dict__
, orgetattr(obj)
here. My example usesglobals()
.您可以使用字典(映射),并利用使用元组作为键的事实。
并不是说这是进行单位转换的最佳方式,而只是调度功能的演示。
我比从 globals() 中选择更喜欢这个,因为它更明确、更安全。
You can use a dictionary (mapping), and take advantage of the fact that you use tuples as keys.
Not saying this is the best way to do unit conversion, but just a demonstration of dispatching functions.
I like this better than picking from globals() because it's more explicit and safer.
这怎么样?
How's this?