在矩阵中获取上方元素(Python)

2 投票
3 回答
557 浏览
提问于 2025-04-17 16:32

我有一个这样的矩阵:

    matrix = [[1,0,1],[0,1,0],[1,1,0]]

(在我实际的问题中,这个矩阵要大得多,但我先简单说。重要的是,它只包含零和一。)

对于矩阵中的每一个元素,我想给变量 'alive' 赋值,表示周围有多少个一。对于水平方向的元素,我是这样做的:

    alive = matrix[i+1] + matrix[i-1]

但现在我还想考虑上面和下面的元素(下面的处理方式可以和上面一样)。

我该如何获取我正在计算周围一的元素正上方的那个元素呢?

3 个回答

0

我觉得你想要的东西可能是这样的:

def get_alive(matrix):
    empty = [0]*(len(matrix[0])+2)
    temp = [empty] + [[0]+row+[0] for row in matrix] + [empty]
    def count(i, j):
        return (sum(temp[i-1][j-1:j+2]) + temp[i][j-1] + temp[i][j+1] +
                sum(temp[i+1][j-1:j+2]))
    rows = range(1, len(temp)-1)
    cols = range(1, len(temp[0])-1)
    return [[count(i, j) for j in cols] for i in rows]

举个例子:

>>> import pprint
>>> matrix = [[1,0,1],[0,1,0],[1,1,0]]
>>> alive = get_alive(matrix)
>>> pprint.pprint(matrix, width=20)
[[1, 0, 1],
 [0, 1, 0],
 [1, 1, 0]]
>>> pprint.pprint(alive, width=20)
[[1, 3, 1],
 [4, 4, 3],
 [2, 2, 2]]
1

你可以使用numpy的数组功能来计算整个矩阵中的活跃状态:

import numpy as np

 # Your matrix defined as numpy array:
 matrix = np.array([[ 1, 0, 1 ], [ 0, 1, 1 ], [ 0, 0, 1 ]])

 # Get the size of the matrix
 nn = matrix.shape[0]

 # Create alive matrix by summing the four neighboring fields:
 alive = np.fromfunction(lambda i, j: matrix[(i+1)%nn, j] + matrix[(i-1)%nn, j]
    + matrix[i, (j+1)%nn] + matrix[i, (j-1)%nn], (nn, nn), dtype=int)

通过numpy数组,你可以直接用 alive[i, j] 来访问元素。

2

我通常喜欢用类似下面的方式来简单访问多维列表:

matrix = [[1,0,1],[0,1,0],[1,1,0]]
valatpos = dict()
for row, inner in enumerate(matrix):
  for col, val in enumerate(inner):
    valatpos[row,col] = val

然后,在比较的时候,你可以调用这个来获取一个值,可以上下或左右移动行或列,随意组合。

valatpos[i + 1, j] # Below
valatpos[i - 1, j] # Above
valatpos[i, j - 1] # Left
valatpos[i, j + 1] # Right
valatpos[i + 1, j + 1] # Below, Right    

我更喜欢这种方式,而不是:

matrix[i + 1][j]

撰写回答