检查变量是None还是numpy.array

2024-05-14 21:09:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我在表中查找键是否有关联数组。通过设计,mytable.__getitem__()somtimes返回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() or table[w.lower()].any(),那么如果它不匹配,我会遇到:

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

我一定是错过了正确的方法,怎么办?


Tags: ornumpynoneisvaluestackmytabletable
3条回答

这应该管用:

value = table[w]
if value is None:
    value = table[w.lower()]
if type(value) is numpy.ndarray:
    #do numpy things
else
    # Handle None

尽管上面的方法可行,但我建议保持签名的简单性和一致性,即表[w]应该始终返回numpy数组。如果没有,则返回空数组。

使用^{}

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

value = table.get(w, table.get(w.lower()))

所以如果table[w]不存在,你会得到table[w.lower()],如果不存在,你会得到None

相关问题 更多 >

    热门问题