简体   繁体   中英

How can I manipulate a list of lists?

How can i iterate through a list of lists so as to make any of the lists with a "1" have the top(0), top left(0), top right(0), bottom(0), bottom right(0),bottom left(0) also become a "1" as shown below? making list 1 become list 2

list_1 =[[0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0],
         [0,0,0,1,0,0,0,0],
         [0,0,0,0,0,0,0,0]]


list_2 =[[0,0,0,0,0,0,0,0],
         [0,0,1,1,1,0,0,0],
         [0,0,1,1,1,0,0,0],
         [0,0,1,1,1,0,0,0]]

This is a common operation known as "dilation" in image processing. Your problem is 2-dimensional, so you would be best served using

  • a more appropriate 2-d data structure than a list of lists, and
  • an already available library function, rather than reinvent the wheel

Here is an example using a numpy ndarray and scipy's binary_dilation respectively:

>>> import numpy as np
>>> from scipy import ndimage
>>> a = np.array([[0,0,0,0,0,0,0,0],
                  [0,0,0,0,0,0,0,0],
                  [0,0,0,1,0,0,0,0],
                  [0,0,0,0,0,0,0,0]], dtype=int)
>>> ndimage.binary_dilation(a, structure=ndimage.generate_binary_structure(2, 2)).astype(a.dtype)
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0, 0]])

With numpy, which is more suitable to manipulate 2D list in general. If you're doing image analysis, see @wim answer. Otherwise here is how you could manage it with numpy only.

> import numpy as np
> list_1 =[[0,0,0,0,0,0,0,0],
           [0,0,0,0,0,0,0,0],
           [0,0,0,1,0,0,0,0],
           [0,0,0,0,0,0,0,0]]
> l = np.array(list_1) # convert the list into a numpy array
> pos = np.where(l==1) # get the position where the array is equal to one
> pos
(array([2]), array([3])) 

# make a lambda function to limit the lower indexes:
get_low = lambda x: x-1 if x>0 else x
# get_high is not needed.

# slice the array around that position and set the value to one
> l[get_low(pos[0]):pos[0]+2,  
    get_low(pos[1]):pos[1]+2] = 1

> l
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0, 0],
       [0, 0, 1, 1, 1, 0, 0, 0]])

> corner
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 1]])

> p = np.where(corner==1)
> corner[get_low(p[0]):p[0]+2,  
         get_low(p[1]):p[1]+2] = 1
> corner
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 1],
       [0, 0, 0, 0, 0, 0, 1, 1]])

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM