python - 检查变量是否为 None 或 numpy.array

标签 python numpy

我在表中查找键是否有关联的数组。根据设计,我的 table.__getitem__() 有时返回 None 而不是 KeyError-s。我希望这个值是 None,或者是与 w 关联的 numpy 数组。

value = table[w] or table[w.lower()]
# value should be a numpy array, or None
if value is not None:
    stack = np.vstack((stack, value))

只有当我使用上面的代码,并且第一次查找是匹配时,我才会得到:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

如果我使用 value = table[w].any() 或 table[w.lower()].any(),那么如果不匹配,我预计会遇到:

AttributeError: 'NoneType' object has no attribute 'any'

我一定缺少执行此操作的正确方法,该怎么办?

最佳答案

if type(value) is numpy.ndarray:
    #do numpy things
else
    # Handle None

虽然上面的方法可行,但我建议保持签名简单且一致,即 table[w] 应始终返回 numpy 数组。如果为 None,则返回空数组。

关于python - 检查变量是否为 None 或 numpy.array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39567422/

相关文章:

python - Pandas 在过滤时将 int 提升为 float

python - gensim 文件未找到错误

python - 如何计算极坐标中窗口和常数向量的点积?

python - 使用沿一个轴应用的 argmin 索引索引多维数组

python - 如何从同样动态创建 salt 状态的循环中要求动态创建的 salt 状态?

python - 如何计算 50x20 矩阵的类内散布

python - python 中的 4 维零数组

python - 将 Django 时间变量显示为完整的小时、分钟 am/pm

python - 类与列表(访问器编码风格)

python - 如何打印变量中包含的 unicode 字符串的值