Python np数组作为可选参数
我有一个函数,可以接受两个可选的Python np数组作为可选参数,python,arrays,numpy,Python,Arrays,Numpy,我有一个函数,可以接受两个可选的np.array作为参数。如果两者都被传递,函数应该执行一些任务 def f(some_stuff, this=None, that=None): ...do something... if this and that: perform_the_task() 如果未传递任何可选参数,则此操作与预期一样有效。如果我传递了一个np.array,那么我就得到了错误 ValueError: The truth value of an arr
np.array
作为参数。如果两者都被传递,函数应该执行一些任务
def f(some_stuff, this=None, that=None):
...do something...
if this and that:
perform_the_task()
如果未传递任何可选参数,则此操作与预期一样有效。如果我传递了一个np.array
,那么我就得到了错误
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
是否有更简洁的方法来检查是否通过了额外的参数?我想我可以安全地假设,如果它们被传递,那么它们将是np.array
首先,您可以假设它们是正确的类型(特别是如果您是唯一使用代码的人)。只需将其添加到文档中即可。(被接受的答案在解释鸭子打字时甚至叹了口气)
你得到的例外很常见,而且都结束了,就像
就你而言
if this is not None and that is not None
你会完成你想要的。问题不在于“和”,而在于数组
if np.array([True, False]):
foo()
从numpy的角度来看是不明确的,因为数组的一些值是真的,但不是所有的。。。那么它应该返回什么呢?。这种行为与列表的行为明显不一致(我相信您当前的代码遵循了建议的检查列表是否为无或空的方法)
如果您正在考虑一种JavaESK方法,根据传递的参数数量来重载函数,那么您的pythonical思想还不够。您当然可以将该条件之后的任何内容发送到另一个函数以“简洁”地处理它。以下也可以
def f(some_stuff, this=None, that=None):
...do something...
perform_the_task(this,that)
def perform_the_task(this,that):
if this is None or that is None: return
raise NotImplementedException
正如您在侧栏中看到的,这个
ValueError
以前出现过很多次
问题的核心是numpy数组可以返回多个真值,而许多Python操作只需要一个真值
我将举例说明:
In [140]: this=None
In [141]: if this:print 'yes'
In [142]: if this is None: print 'yes'
yes
In [143]: this=np.array([1,2,3])
In [144]: if this: print 'yes'
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [145]: if this is None: print 'yes'
In [146]: this and this
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [147]: [1,2,3] is None
Out[147]: False
In [148]: this is None
Out[148]: False
In [149]: [1,2,3]==3 # one value
Out[149]: False
In [150]: this == 3 # multiple values
Out[150]: array([False, False, True], dtype=bool)
像not
这样的逻辑操作通常返回简单的True/False,但对于数组,它们为数组的每个元素返回一个值
In [151]: not [1,2,3]
Out[151]: False
In [152]: not None
Out[152]: True
In [153]: not this
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
在函数中,如果不提供f
2个或多个参数,这个
和那个
将有值无
。使用进行测试的安全方法是无
或不是无
:
def f(some_stuff, this=None, that=None):
...do something...
if this is not None and that is not None:
perform_the_task()