检查数值为零时的多条件声明-python 有一个问题,但是这个问题也要考虑在条件中检查变量的类型。

检查数值为零时的多条件声明-python 有一个问题,但是这个问题也要考虑在条件中检查变量的类型。,python,conditional-statements,zero,typechecking,or-operator,Python,Conditional Statements,Zero,Typechecking,Or Operator,给定0 if not variable else variable样式语句,它将允许空对象通过,例如 >>> x, y = None, [] >>> 0 if not(x and y) else x / y 0 >>> x, y = None, 0 >>> 0 if not(x and y) else x / y 0 >>> x, y = 0, 1 >>> 0 if not(x and y

给定
0 if not variable else variable
样式语句,它将允许空对象通过,例如

>>> x, y = None, []
>>> 0 if not(x and y) else x / y
0
>>> x, y = None, 0
>>> 0 if not(x and y) else x / y
0
>>> x, y = 0, 1
>>> 0 if not(x and y) else x / y
0
>>> x, y = 2, ""
>>> 0 if not(x and y) else x / y
0
>>> x, y = 2, 1
>>> 0 if not(x and y) else x / y
2
但是,如果我显式地检查变量的值是否为零,则会更好一些,因为当两种类型不同或无法与零值进行比较时,会产生错误,例如:

>>> x, y = 2, ""
>>> 0 if (x&y) == 0 else x / y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'int' and 'str'
>>> x,y = "",""
>>> 0 if (x&y) == 0 else x / y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'str' and 'str'
>>> x,y = [],[]
>>> 0 if (x&y) == 0 else x / y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'list' and 'list'
此外,当变量类型是数值型但有些不同时,这会导致问题:

>>> x, y = 1, 3.
>>> 0 if (x|y) == 0 else math.log(x/y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'int' and 'float'
因此,问题是:

  • 用什么pythonic方法检查多个变量的值为零?
  • 另外,重要的是不要像布尔类型那样滑动并引发错误,而不是让它返回零,如何才能做到这一点?
  • 对于检查
    (x | y)==0且x和y为浮点类型的
    应如何解决
    类型错误:不支持的|:'float'和'float'
    操作数类型?
考虑到“简单胜于复杂”,我想说,如果你想检查一个值是否具有除布尔值以外的数值类型(注意:布尔值在Python中是一种数值类型,
1/True
是有效的),最具Python风格的方法就是明确地做到这一点,没有任何按位操作或依赖隐式检查

import numbers

if not isinstance(y, numbers.Number) or type(y) is bool:
    raise TypeError("y must be a number")
return x / y if y else 0

如果您的数值运算取决于两个操作数的确切类型,那么显而易见的(因此是pythonic)解决方案是显式检查两个操作数的类型或处理预期的异常。显式检查如何:“0 in(x,y)”?@A.Haaji这将在布尔值上失败:
0 in(True,False)=>真的
在(x,y)
中的
0和
不(x和y)
之间有区别吗?
any(对于(x,y)中的i,i是0)怎么样?
酷!不知道
数字
有一些很酷的元和类!
>>> x, y = 1., 3.
>>> 0 if (x&y) == 0 and type(x) == type(y) == float else math.log(x/y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'float' and 'float'
>>> x, y = 1., 3.
>>> 0 if (x&y) == 0. and type(x) == type(y) == float else math.log(x/y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'float' and 'float'
>>> x, y = 1, 3
>>> 0 if (x&y) == 0 and type(x) == type(y) == float else math.log(x/y)
-1.0986122886681098
import numbers

if not isinstance(y, numbers.Number) or type(y) is bool:
    raise TypeError("y must be a number")
return x / y if y else 0