【问题标题】:Python - Simple Question: Numpy Matrix, LoopPython - 简单问题:Numpy 矩阵、循环
【发布时间】:2018-11-21 23:28:13
【问题描述】:

我对 python 还很陌生,我正在尝试理解以下代码:

import numpy as np
n=4
matrix=np.zeros((n,n))
for j in range (0,n):
    for i in range (n-1,n-j-2,-1):
        matrix[i,j]=2*n-i-j-1
print (matrix)

如果有人能帮助我了解每一行是如何执行的,以及如何使用循环重新评估代码,我将不胜感激。

提前致谢!

【问题讨论】:

  • 简而言之:它创建了一个 4 x 4 数组,其中左下角三角形中的每个单元格都有值 i - j + 1,其中 i 是行索引,j 是列索引。如果这不能解决问题,您需要更具体地说明您不了解的内容。
  • 感谢您的及时回复!我的问题是我怎么知道左下三角形是执行矩阵公式的地方。对不起,如果它太明显了,但我是一个完全的初学者
  • 外部for 循环遍历行索引。内部 for 循环遍历列,但只迭代到等于当前行号的列号。

标签: python python-2.7 loops numpy matrix


【解决方案1】:

您可以添加以下打印语句,循环将在每次迭代时自行解释:

n=4
matrix=np.zeros((n,n))
for i in range (0,n):
    for j in range(0,i+1):
        print(f'inserting {i-j+1} into the matrix at row index {i}, columns index {j}')
        matrix[i,j]=i-j+1

当你运行它时,你会得到这个输出:

inserting 1 into the matrix at row index 0, columns index 0
inserting 2 into the matrix at row index 1, columns index 0
inserting 1 into the matrix at row index 1, columns index 1
...
inserting 3 into the matrix at row index 3, columns index 1
inserting 2 into the matrix at row index 3, columns index 2
inserting 1 into the matrix at row index 3, columns index 3

你的矩阵像以前一样被填充:

>>> matrix
array([[1., 0., 0., 0.],
       [2., 1., 0., 0.],
       [3., 2., 1., 0.],
       [4., 3., 2., 1.]])

仅供参考:

>>> matrix
array([[1., 0., 0., 0.],   #<- "row" index 0
       [2., 1., 0., 0.],   #<- "row" index 1
       [3., 2., 1., 0.],   #<- "row" index 2
       [4., 3., 2., 1.]])  #<- "row" index 3

      # ^      ...  ^
      # "col" 0     "col" 3

【讨论】:

  • 非常感谢,这真的很有帮助!
【解决方案2】:
import numpy as np
n=4

我们首先设置一个 4x4 矩阵,所有坐标都设置为空:

matrix=np.zeros((n,n))         

我们通过循环遍历行和列来设置新的坐标值。首先我们遍历行,从索引 0 到 n-1:

for i in range (0,n): 

接下来我们遍历列。现在,请注意我们只遍历那些索引小于或等于当前行的列(即从 0 到 i)。这样我们就可以确保我们设置的值在矩阵的对角线上或之下:

    for j in range(0,i+1):     

最后,我们为当前坐标设置所需的值:

        matrix[i,j]=i-j+1
print(matrix)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多