[英]Is there a python built-in function to get 0 for None
Is there a built-in function in python which does the following: python中是否有内置函数,它执行以下操作:
def none_safe(int_value):
return int_value if int_value is not None else 0
Assuming that the only possible inputs are None
and instances of int
: 假设唯一可能的输入是None
和int
实例:
int_value or 0
Some APIS, such as dict.get
, have an argument where you can pass the default. 某些APIS(例如dict.get
)有一个参数,您可以在其中传递默认值。 In this case it's just a value, but note that or
is evaluated lazily whereas a function argument is necessarily evaluated eagerly. 在这种情况下,它只是一个值,但请注意or
被懒惰地评估,而函数参数必须急切地评估。
Other APIs, such as the constructor of collections.defaultdict
, take a factory to construct defaults, ie you would have to pass lambda: 0
(or just int
since that is also a callable that returns 0
), which avoids the eagerness if that's a problem, as well as the possibility of other falsy elements. 其他API,例如collections.defaultdict
的构造函数,需要一个工厂来构造默认值,即你必须传递lambda: 0
(或者只是int
因为它也是一个返回0
的可调用对象),这样可以避免这种情况下的热情。问题,以及其他虚假元素的可能性。
Even safer (usually) is to just return 0 for any value that can't be an int
更安全(通常)只是为任何不能为int
值返回0
def none_safe(int_value):
try:
return int(int_value)
except (TypeError, ValueError):
return 0
Other variations might use isinstance
or similar depending on your exact requirements 其他变体可能会使用isinstance
或类似,具体取决于您的具体要求
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.