如何操作列表列表?

时间:2016-01-28 19:02:20

标签: python nested-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]]

2 个答案:

答案 0 :(得分:1)

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

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

以下是分别使用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]])

答案 1 :(得分:0)

使用numpy,它更适合一般操作2D列表。如果您正在进行图像分析,请参阅@wim answer。否则,这里是你如何只用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