使用Python,在行和列中提取矩阵的上一个和下一个项

时间:2017-04-22 13:50:16

标签: python list matrix arraylist

我有以下表格的列表矩阵。

Matrix=[[[0,1,2],[3,4,5],[6,7,8],[9,10,11]], [[12,13,14],[15,16,17],[18,19,20],[21,22,23]], [[24,25,26],[27,28,29],[30,31,32],[33,34,35]]]

例如,我选择Matrix[i][j],因此我想提取Matrix[i-1][j-1], Matrix[i-1][j], Matrix[i-1][j+1], Matrix[i-1][j-1], Matrix[i][j-1], Matrix[i][j+1], Matrix[i+1][j-1], Matrix[i+1][j] and Matrix[i+1][j+1]

我可以循环吗?

1 个答案:

答案 0 :(得分:0)

这应该是你想要的。

首先让我们获得i & j

的所有独特组合
import itertools
import numpy

def uc(nums):
    return set(itertools.product(*((num+1, num-1, num) for num in nums)))

nums = [1,2]

idx = uc(nums)

>>>{(0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)}

m = np.array(Matrix)

array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8],
        [ 9, 10, 11]],

       [[12, 13, 14],
        [15, 16, 17],
        [18, 19, 20],
        [21, 22, 23]],

       [[24, 25, 26],
        [27, 28, 29],
        [30, 31, 32],
        [33, 34, 35]]])

然后我们可以使用numpy中元组索引的强大功能来选择与这些索引匹配的所有行。

[m[idx_] for idx_ in idx]

[array([3, 4, 5]),
 array([18, 19, 20]),
 array([21, 22, 23]),
 array([27, 28, 29]),
 array([15, 16, 17]),
 array([33, 34, 35]),
 array([30, 31, 32]),
 array([ 9, 10, 11]),
 array([6, 7, 8])]