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

时间:2019-02-26 19:27:29

标签: python list matrix grid diagonal

我有一个不同数字的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]。

4 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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)

答案 2 :(得分: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']

答案 3 :(得分:0)

在@blhsing答案中,我认为次数迭代应该改为min(len(m) - 1 - row, len(m[0]) - 1 - col)

让我们看一个例子: 想象一个2行的矩阵:

[
 [0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4],
]

比方说,起点是第一行,元素编号4,如果我们使用原始计算(即min((len(m), len(m[0]))) - max((row, col))),我们将得到(min(2,5)-max(0 ,3))= 2-3 = -1。

如果我们使用建议的一个(即min(len(m) - 1 - row, len(m[0]) - 1 - col)),我们将得到min(2-1-0,5-1-3)= min(1,1)= 1。 >