有一个关于Idiomatic Python 的问题 - 检查是否为零,但考虑这个问题时还要检查条件内的变量类型。
给定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'
因此,通常在定义检查数值的条件时,代码之类的是否0 if (x|y) == 0 else x/y
更 Pythonic/更合适?
但这也是有问题的,因为它让布尔类型滑过,这会导致一些非常令人不安的事情ZeroDivisionError
发生ValueError
,例如:
>>> x,y = True, True
>>> 0 if (x&y) == 0 else x / y
1
>>> x,y = True, False
>>> 0 if (x&y) == 0 else x / y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> x,y = False, True
>>> 0 if (x&y) == 0 else x / y
0
>>> x,y = False, True
>>> 0 if (x&y) == 0 else math.log(x/y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
此外,当变量类型是数字但有些不同时,这会导致问题:
>>> 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'
还有_or
操作员不能浮动的事实,这很奇怪:
>>> 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
所以问题是:
- 检查零值的多个变量的pythonic方法是什么?
- 此外,重要的是不要喜欢布尔类型的 slip 并引发错误而不是让它返回零,这怎么办?
- 以及如何
TypeError: unsupported operand type(s) for |: 'float' and 'float'
解决检查(x|y) == 0
x 和 y 作为浮点类型的问题?