如何操作列表列表?

How can I manipulate a list of lists?

我如何遍历列表的列表以使任何带有“1”的列表具有顶部(0)、左上(0)、右上(0)、底部(0) , 右下(0), 左下(0) 也变成“1” 如下图?使列表 1 成为列表 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]]

这是图像处理中称为"dilation"的常见操作。您的问题是二维的,因此最好使用

  • 比列表的列表更合适的二维数据结构,
  • 一个已经可用的库函数,而不是重新发明轮子

这是一个分别使用 numpy ndarray 和 scipy 的 binary_dilation 的示例:

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

用numpy,比较适合操作一般的二维列表。如果您正在进行图像分析,请参阅@wim 的回答。否则这里是你如何只用 numpy 来管理它。

> 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