python - List of objects: how to extract attributes from a particular region or slice? -


this image numpy docs left me wondering. if multidimensional list (or ndarray) containing objects attribute in common, how can 1 extract specific parts?

enter image description here

i have read other questions how extract attributes entire list , extracting rows , columns easy using list comprehensions, can't wrap head around how it, instance, 2nd , 4th slices shown in image, especially 4th slice.

this useful board game i'm making, slice board , check, example, if group of tiles have particular value or if share specific attribute.

you want check if have attribute in common can reduce 1d-case raveling result of indexing.

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

since seems 1d cases solveable (with list comprehensions) might trick. list comprehensions have aware multidimensional arrays should ravelled or flattened (see numpy documentation) if don't want array of axis result.

for simple cases might want use np.all function without flatten or ravel:

#just check if multiplicatives of 2 np.all((array[2::2,2::2] % 2) == 0) # gives true #just check if multiplicatives of 3 np.all((array[2::2,2::2] % 3) == 0) # gives false 

but there way: numpy provides np.nditer iterator (http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html) , can pretty fancy stuff one. easy example:

#supposing check attribute def check_for_property(array, property_name, property_state):    #property_name: str (the name of property want check(    #property_state: (check if property_name property of elements matches one)    #the returns act shortcut loop stopped after first mismatch.    #it returns true if complete loop passed.    in np.nditer(array):        if hasattr(i, property_name):           if getattr(i, property_name) != property_state:               return false #property has not same value assigned        else:           return false # if element hasn't got property return false    return true #all elements have property , equal 'property_state' 

in case want small (and check relativly easy) list-comprehension np.all , np.nditer like:

np.all(np.array([i.property in np.nditer(array[2::2,2::2])]) == property_state) 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -