2

有一个关于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) == 0x 和 y 作为浮点类型的问题?
4

1 回答 1

4

考虑到PEP 20的“简单胜于复杂”,我会声称,如果您想检查一个值是否具有布尔以外的数字类型(请注意:布尔在 Python 中1/True一种数字类型,并且是有效的),最pythonic的方法是明确地做到这一点,而不需要任何按位操作或依赖隐式检查。

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
于 2016-01-25T15:26:34.460 回答