【问题标题】:Get all the diagonals in a matrix(nested list) from any position in Python从Python中的任何位置获取矩阵(嵌套列表)中的所有对角线
【发布时间】:2020-10-21 23:12:28
【问题描述】:

我正在寻找一种方法来获取字段 8x8 的所有对角线,表示为列表列表

我有以下矩阵:

field = [
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0]
]

如何从任何位置对角更改字段单元格的值 例如:(起始位置为字段[3][4])

field = [
  [0, x, 0, 0, 0, 0, 0, x],
  [0, 0, x, 0, 0, 0, x, 0],
  [0, 0, 0, x, 0, x, 0, 0],
  [0, 0, 0, 0, x, 0, 0, 0],
  [0, 0, 0, x, 0, x, 0, 0],
  [0, 0, x, 0, 0, 0, x, 0],
  [0, x, 0, 0, 0, 0, 0, x],
  [x, 0, 0, 0, 0, 0, 0, 0]
]

【问题讨论】:

  • 可能使用 numpy 更好?查看np.diag
  • 欢迎来到 SO。这不是讨论论坛或教程。请使用tour 并花时间阅读How to Ask 以及该页面上的其他链接。花一些时间与the Tutorial 练习示例。它会让你了解 Python 提供的工具来帮助你解决问题。

标签: python list matrix nested diagonal


【解决方案1】:

我还没有测试过,但是试试这个:

def change_diag(mat, x, y):
    pointer_x_less = x
    pointer_x_more = x
    pointer_y_less = y
    pointer_y_more = y

    while pointer_x_less >= 0 or pointer_x_more < len(mat[0]) or pointer_y_less >= 0 or pointer_y_more < len(mat):
        try:
            mat[pointer_x_more][pointer_y_more] = 'x'
            mat[pointer_x_more][pointer_y_less] = 'x'
            mat[pointer_x_less][pointer_y_more] = 'x'
            mat[pointer_x_less][pointer_y_less] = 'x'
        except:
            pass

        pointer_x_less -= 1
        pointer_x_more += 1
        pointer_y_less -= 1
        pointer_y_more += 1

    return mat

【讨论】:

    猜你喜欢
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多