python - 检测非标量和非元组?

标签 python

出于好奇,我试图用短代码来检测 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 来区分 None0 值。

确实没有办法通过强制转换为 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/

相关文章:

Python 示例在测验期间而不是结束时重复答案

python - 在 Ubuntu 上运行 OpenCV 时 GStreamer 发出警告

python - 在Python中逐行将json-ish列表写入csv以获取比特币地址

Python - 如何使用循环缩短这段重复代码?

python - Pandas `to_csv` 无法设置引号

python - 在 Python/Ubuntu 18.04 LTS 上安装 PCL 库

python - 脱脂图像 : how to combine RGB channels?

python - dfitpack.错误 : (m>k) failed for hidden m: fpcurf0:m=1

python - 从一个列表列表中减去另一个列表列表

python - 将单元格设置为等于 pandas 中的值