出于好奇,我试图用短代码来检测 None-Scalar 和 None-tuple 以在 lambda 中使用......即使用 isinstance 很麻烦。
所以可能的值是:
None
(None, 0)
Value
(Value, 1)
到目前为止 not (not x or not x[0])
,适用于情况 1,2,4,但不适用于情况 3
xx = lambda x: not( not x or not x[0] )
xx(None) => False
xx((None,0)) => False
xx(5)
TypeError: 'int' object has no attribute '__getitem__'
最佳答案
您需要某种形式的 is not None
来区分 None
和 0
值。
确实没有办法通过强制转换为 bool 值来区分数字对和数字。非空元组将始终为真,无将始终为假,但数字可以是真也可以是假(当为 0 时)。
您可以在一行中完成此操作,而无需使用 isinstance()
,而是使用 type()
:
lambda x: {tuple: x}.get(type(x), [x])[0] is not None
# or
lambda x: (x[0] if type(x) is tuple else x) is not None
isinstance()
的优点是它可以与子类一起使用。
或者使用标准库导入:
from unittest.mock import ANY
lambda x: x not in [None, (None, ANY)]
这种事情在具有模式匹配的语言中很容易实现。 (Python 可能很快就会出现,请参阅 PEP 622 。)我(ab)使用 ANY
模拟来实现类似的效果。
小心任何
。它通过重写 .__eq__()
和 .__ne__()
来工作,因此它不一定是自反的。
关于python - 检测非标量和非元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62783028/