您只想检查它们是否具有共同的属性,而不是通过分解索引结果将其简化为一维案例。
array = np.arange(25).reshape(5,5)
array[2::2,2::2] # Gives you: array([[12, 14], [22, 24]])
array[2::2,2::2].ravel() #Gives you: array([12, 14, 22, 24])
因为看起来一维案例是可以解决的(使用列表推导),这可能只是诀窍。但是对于列表推导,您必须注意,如果您不想要 axis 的数组作为结果,则应该将多维数组解散或展平(参见 numpy 文档)。
对于简单的情况,您可能只想使用np.all 函数而不使用flatten 或ravel:
#Just check if they are all multiplicatives of 2
np.all((array[2::2,2::2] % 2) == 0) # Gives you True
#Just check if they are all multiplicatives of 3
np.all((array[2::2,2::2] % 3) == 0) # Gives you False
但还有另一种方式:numpy 提供了一个 np.nditer 迭代器 (http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html),你可以用它来做一些漂亮的事情。就像一个非常简单的例子:
#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.nditer 的列表理解可能如下所示:
np.all(np.array([i.property for i in np.nditer(array[2::2,2::2])]) == property_state)