[英]isinstance check if any of the variables has a certain class
I'm having a function that needs to take a different route if any of the parameters is a np.ndarray
. 如果有任何参数是
np.ndarray
,我有一个函数需要采取不同的路线。 I'm checking with isinstance
. 我正在检查
isinstance
。 But I wondered if there might be a more intuitive (and faster) way than using a list comprehension together with any
: 但是我想知道是否有比使用列表理解和
any
方法更直观(更快)的方法:
def func(a, b):
if any([isinstance(i, np.ndarray) for i in [a, b]]):
...
else:
...
I already tried: 我已经尝试过:
if isinstance([a, b], np.ndarray):
but that doesn't work because [a, b]
is a list
... 但这不起作用,因为
[a, b]
是一个list
...
Actually using any
is the most pythonic way because it has been implemented in python like following: 实际上,使用
any
是最Python的方式,因为它已在python中实现,如下所示:
def any(iterable):
for element in iterable:
if element:
return True
return False
And will return True
right after encounter a True item in your iterable thus it's order in best case would be O(1) and in worst case O(n). 并且在遇到您的可迭代项中的True项后立即返回
True
,因此最佳情况下的顺序为O(1),最坏情况下的顺序为O(n)。 And about the isinstance()
it's a built in function and is a pythonic way for checking the objects type. 关于
isinstance()
它是一个内置函数,并且是检查对象类型的Python方法。
Also as a more pythonic way you better to pass a generator expression to any
and let generator function generate the items on demand, instead of a list comprehension and create all the boolean values at once.: 另外,作为一种更加Python化的方式,您最好将生成器表达式传递给
any
生成器表达式,并让生成器函数按需生成项目,而不是列表理解并立即创建所有布尔值。
any(isinstance(i, np.ndarray) for i in [a, b])
As @Padraic said if you are only dealing with two item the best way is using or
operator: 正如@Padraic所说,如果您只处理两个项目,则最好的方法是使用
or
运算符:
if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):
# do stuff
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.