测试输入是否格式良好的数字的最 Pythonic 方法是什么
我有一个函数需要实数(整数或浮点数)作为其输入,并且我试图在对其进行数学运算之前验证该输入。
我的第一直觉是将输入转换为 try- except 块中的浮点数。
try:
myinput = float(input)
except:
raise ValueError("input is not a well-formed number")
我也可以调用 isinstance(mydata, (float, int, long) ) ,但“所有这些都可能是数字”的列表对我来说似乎有点不优雅。
最Pythonic的方法是什么? 还有另一个我忽略的选择吗?
I have a function that expects real numbers (either integers or floats) as its input, and I'm trying to validate this input before doing mathematical operations on it.
My first instinct is to cast inputs as floats from within a try-except block.
try:
myinput = float(input)
except:
raise ValueError("input is not a well-formed number")
I could also call isinstance(mydata, (float, int, long) )
but the list of "all these could be numbers" seems a bit inelegant to me.
What's the most pythonic way of going about it? Is there another option I overlooked?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
引用我的话多少我应该对我的 python 函数/方法进行输入验证吗?:
因此,最好的选择是将类型检查留给 Python。 如果计算失败,Python的类型检查会给出异常,所以如果你自己做,你只是重复代码,这意味着你需要做更多的工作。
To quote myself from How much input validation should I be doing on my python functions/methods?:
Thus, the best option is to leave the type checking up to Python. If the calculation fails, Python's type checking will give an exception, so if you do it yourself, you just duplicate code which means more work on your behalf.
在 Python 2.6 和 3.0 中,添加了数字抽象数据类型的类型层次结构,因此您可以执行检查:
numbers.Real将匹配整数或浮点类型,但不匹配非数字类型或复数(使用numbers.Complex)。 它还会匹配有理数,但想必您也想包括这些。 即:
不幸的是,这一切都是在 Python >=2.6 中进行的,因此如果您正在为 2.5 或更早版本进行开发,则不会有用。
In Python 2.6 and 3.0, a type hierarchy of numeric abstract data types has been added, so you could perform your check as:
numbers.Real will match integral or float type, but not non-numeric types, or complex numbers (use numbers.Complex for that). It'll also match rational numbers , but presumably you'd want to include those as well. ie:
Unfortunately, this is all in Python >=2.6, so won't be useful if you're developing for 2.5 or earlier.
也许您可以结合使用
assert
和isinstance
语句。我认为像下面这样的方式更Pythonic,因为只要您的输入不符合您的要求,您就会抛出异常。 不幸的是,我没有看到比你的更好的有效数字定义。 也许有人会提出更好的主意。
Maybe you can use a combination of
assert
andisinstance
statements.Something like the following is I think a more pythonic way, as you throw an exception whenever your inputs don't follow your requirements. Unfortunately I don't see any better definition of what is a valid number than yours. Maybe someone will come with a better idea.
我不明白这个问题。
有两种语义截然不同的东西被作为“替代品”扔掉。
类型转换是一回事。 它适用于任何支持 __float__ 的对象,这些对象可以是各种各样的对象,其中很少有实际上是数字的。
类型测试是另一回事。 这仅适用于作为特定类集的正确实例的对象。
下面是响应
float
的示例类,但仍然不是数字。“实数(整数或浮点数)”问题通常是无关紧要的。 许多东西都是“数字”的,可以在数字运算中使用,但不是整数或浮点数。 例如,您可能已经下载或创建了有理数包。
过度验证输入是没有意义的,除非您有一个不适用于某些类型的算法。 这些很少见,但有些计算需要整数,特别是这样它们可以进行整数除法和余数运算。 对于这些,您可能想要断言您的值是整数。
I don't get the question.
There are two things with wildly different semantics tossed around as "alternatives".
A type conversion is one thing. It works with any object that supports
__float__
, which can be quite a variety of objects, few of which are actually numeric.A type test is another thing. This works only with objects that are proper instances of a specific set of classes.
Here's the example class that responds to
float
, but is still not numeric.The question "real numbers (either integers or floats)" is generally irrelevant. Many things are "numeric" and can be used in a numeric operation but aren't ints or floats. For example, you may have downloaded or created a rational numbers package.
There's no point in overvalidating inputs, unless you have an algorithm that will not work with some types. These are rare, but some calculations require integers, specifically so they can do integer division and remainder operations. For those, you might want to assert that your values are ints.