#Supposing you check for an attribute
def check_for_property(array, property_name, property_state):
#property_name: str (The name of the property you want to check(
#property_state: anything (Check if the property_name property of all elements matches this one)
#The returns act as a shortcut so that the for loop is stopped after the first mismatch.
#It only returns True if the complete for loop was passed.
for i in np.nditer(array):
if hasattr(i, property_name):
if getattr(i, property_name) != property_state:
return False #Property has not the same value assigned
else:
return False # If this element hasn't got this property return False
return True #All elements have the property and all are equal 'property_state'
如果您希望它很小(并且您的检查相对容易),那么使用np.all和{}的列表理解可以如下所示:
np.all(np.array([i.property for i in np.nditer(array[2::2,2::2])]) == property_state)
您只需要检查它们是否有共同的属性,然后通过遍历索引的结果将其缩减为1D大小写。在
因为看起来1D案例是可以解决的(有列表理解),这可能就是诀窍。但是对于列表理解,如果您不想得到
axis
的数组,那么多维数组应该被分解或展平(参见numpy文档)。在对于简单的情况,您可能只想使用不带
^{pr2}$flatten
或ravel
的np.all
函数:但是还有另一种方法:numpy提供了一个
np.nditer
迭代器(http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html),你可以用这个迭代器做一些非常奇特的事情。举个简单的例子:如果您希望它很小(并且您的检查相对容易),那么使用}的列表理解可以如下所示:
np.all
和{相关问题 更多 >
编程相关推荐