我在表中查找键是否有关联的数组。根据设计,我的 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/