如何从特定元素中获取矩阵/网格的对角元素?

问题描述 投票:1回答:3

我有一个8x8不同数字的网格,我想得到包含给定起始位置的对角线元素。这是一个例子

l = [[str(randint(1,9)) for i in range(8)] for n in range(8)]

>> [
[1 5 2 8 6 9 6 8]
[2 2 2 2 8 2 2 1]
[9 5 9 6 8 2 7 2]
[2 8 8 6 4 1 8 1]
[2 5 5 5 4 4 7 9]
[3 9 8 8 9 4 1 1]
[8 9 2 4 2 8 4 3]
[4 4 7 8 7 5 3 6]
]

如何从x = 4和y = 3的位置获取对角线(所以列表中的第4个列表和第5个元素)?所以我想要的对角线是[5,2,6,4,4,1,3]。

python list matrix grid diagonal
3个回答
2
投票

您可以根据xy的差异计算对角线左上角项目的行和列,以及基于两个边界中较低者与起始行和列中较高者之间差异的迭代次数:

def diagonal(m, x, y):
    row = max((y - x, 0))
    col = max((x - y, 0))
    for i in range(min((len(m), len(m[0]))) - max((row, col))):
        yield m[row + i][col + i]

以便:

m = [
    [1, 5, 2, 8, 6, 9, 6, 8],
    [2, 2, 2, 2, 8, 2, 2, 1],
    [9, 5, 9, 6, 8, 2, 7, 2],
    [2, 8, 8, 6, 4, 1, 8, 1],
    [2, 5, 5, 5, 4, 4, 7, 9],
    [3, 9, 8, 8, 9, 4, 1, 1],
    [8, 9, 2, 4, 2, 8, 4, 3],
    [4, 4, 7, 8, 7, 5, 3, 6],
]
print(list(diagonal(m, 4, 3)))

输出:

[5, 2, 6, 4, 4, 1, 3]

0
投票

这就是我想出的。这不是很美,但它完成了工作。

def get_diagonal(full_grid, y, x):
    if x > y:
        while y >= 1:
            x -= 1
            y -= 1
    else:
        while x >= 1:
            x -= 1
            y -= 1
    diagonal = []
    while x < len(grid) and y < len(grid[0]):
        diagonal.append(grid[x][y])
        x += 1
        y += 1
    return diagonal

grid = [
    [1, 5, 2, 8, 6, 9, 6, 8],
    [2, 2, 2, 2, 8, 2, 2, 1],
    [9, 5, 9, 6, 8, 2, 7, 2],
    [2, 8, 8, 6, 4, 1, 8, 1],
    [2, 5, 5, 5, 4, 4, 7, 9],
    [3, 9, 8, 8, 9, 4, 1, 1],
    [8, 9, 2, 4, 2, 8, 4, 3],
    [4, 4, 7, 8, 7, 5, 3, 6]]

get_diagonal(grid, 5, 3)

0
投票

沿着行使用“y”和沿着垂直方向使用“x”对我来说似乎是违反直觉的,所以我交换了它们。如果您可以将索引设置为零,那么这对我有用:

from random import randint

l = [[str(randint(1,9)) for i in range(8)] for n in range(8)]

# Show the grid
for row in l:
    print(' '.join([str(n) for n in row]))

# Give the initial position, then follow the diagonal down and
# to the right until you run out of rows or columns.
x_pos = 1 
y_pos = 3
diag = []
while x_pos < len(l[0]) and y_pos < len(l):
    diag.append(l[y_pos][x_pos])
    x_pos += 1
    y_pos += 1

print(diag)

样本输出:

1 3 8 7 3 1 5 2
4 5 8 6 9 4 3 2
2 6 1 3 8 6 8 1
7 1 8 2 7 4 7 4
9 5 5 5 5 2 3 1
8 5 9 7 2 7 1 8
3 3 3 4 2 9 8 3
3 2 8 6 2 4 4 8
['1', '5', '7', '2', '4']
© www.soinside.com 2019 - 2024. All rights reserved.