对象列表:如何从特定区域或切片提取属性?

2024-05-17 19:03:20 发布

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

这张照片让我很疑惑。如果它是一个多维列表(或ndarray),包含具有共同属性的对象,那么如何从特定的部分提取它呢?

enter image description here

我也读过其他关于如何从整个列表中提取属性的问题,以及如何使用列表理解从行和列中提取属性很容易,但我无法完全理解如何做,例如,对于图像中显示的第二和第四个切片,尤其是第四个切片。在

这对我正在制作的棋盘游戏很有用,我可以将棋盘切成薄片,然后检查,例如,一组瓷砖是否具有特定的值,或者它们是否共享特定的属性。在


Tags: 对象图像游戏列表棋盘属性切片照片
1条回答
网友
1楼 · 发布于 2024-05-17 19:03:20

您只需要检查它们是否有共同的属性,然后通过遍历索引的结果将其缩减为1D大小写。在

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])

因为看起来1D案例是可以解决的(有列表理解),这可能就是诀窍。但是对于列表理解,如果您不想得到axis的数组,那么多维数组应该被分解或展平(参见numpy文档)。在

对于简单的情况,您可能只想使用不带flattenravelnp.all函数:

^{pr2}$

但是还有另一种方法: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.all(np.array([i.property for i in np.nditer(array[2::2,2::2])]) == property_state)

相关问题 更多 >