【问题标题】:List of all diagonals in a matrix without using numpy - Python 3不使用 numpy 的矩阵中所有对角线的列表 - Python 3
【发布时间】:2019-04-23 12:48:20
【问题描述】:

假设我得到了以下矩阵:

[[5,4,3,2], [8,7,6,5], [4,3,2,0]]

我想创建 2 个单独的函数来创建从右到左和从左到右的所有对角线列表,而不使用 numpy 模块!

例如:

[[4], [8,3], [5,7,2], [4,6,0], [3,5], [2]]   # these are the right to left diagonals

我尝试了几种不同的方法,但都没有成功。另外,我大量扫描堆栈溢出以寻找答案,但没有找到任何不包含 numpy 的内容。

编辑:这是我编写的用于处理某些对角线的代码:

L = [[5, 4, 3, 2], [8, 7, 6, 5], [4, 3, 2, 0]]


def search_diagonally_rtl(matrix):
    num_of_rows = len(matrix)
    num_of_cols = len(matrix[0])
    diag_mat = list()
    for i in range(0, num_of_rows):
        diag_mat.append([matrix[i][0]])
    row_index = 0
    for row in diag_mat:
        for k in range(0, row_index):
            i = k
            j = 1
            while i >= 0:
                row.append(matrix[i][j])
                i = i - 1
                j = j + 1
        row_index += 1

输出为:[[5], [8, 4], [4, 4, 7, 3]]

但应该是:[[5], [8, 4], [4, 7, 3]]

【问题讨论】:

  • 请添加您自己实现的代码并告诉我们其背后的想法。
  • @Irreducible 感谢您的关注。但是我已经删除了我所有的工作,因为到目前为止我没有成功,所以很遗憾我没有什么可显示的。
  • 阅读How to Ask你会发现SO不是一个为你写代码的社区。您应该添加具有所需输入输出行为的代码和示例。拥有所有这些信息的人将能够帮助您了解您的代码/想法中的错误在哪里
  • @Irreducible 谢谢!稍后会添加代码!
  • @Irreducible 好吧,我写了一个应该处理一些对角线的代码,但它似乎有一些问题。你可以看看吗?

标签: python-3.x matrix


【解决方案1】:
def diag1(x, startline):
    out = []
    line = startline
    col = 0
    while line < len(x) and col < len(x[0]):
        out.append(x[line][col])
        line +=1
        col += 1
    return out


def diag2(x, startcol):
    out = []
    line = 0
    col = startcol
    while line < len(x) and col < len(x[0]):
        out.append(x[line][col])
        line +=1
        col += 1
    return out


def diag(x):
    out = []
    for startline in range(len(x) - 1, -1, -1):
        out.append(diag1(x, startline))
    for startcol in range(1, len(x[0])):
        out.append(diag2(x, startcol))
    return out


x = [[5,4,3,2], [8,7,6,5], [4,3,2,0]]
print(diag(x))  # [[4], [8, 3], [5, 7, 2], [4, 6, 0], [3, 5], [2]]

diag1 从矩阵的左边界开始并返回对角线,而diag2 从上边界开始。 diag 结合了这两种方法。
另一个方向的对角线几乎不需要做任何调整。

【讨论】:

    猜你喜欢
    • 2011-09-12
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 2012-04-15
    相关资源
    最近更新 更多