简体   繁体   English

Python For循环-关于第二个循环的问题

[英]Python For Loop - Question about second loop

I am just starting to learn how to code in python and I am trying to get around understanding the following code: 我刚刚开始学习如何使用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) 

I would greatly appreciate if someone could please help me understand how each line executes and how the code is revaluated with the loop. 如果有人可以帮助我理解每一行的执行方式以及如何通过循环重新评估代码,我将不胜感激。 Especially how can I interpret the second "for" loop regarding "i" Thanks in advance! 特别是我该如何解释与“ i”有关的第二个“ for”循环,谢谢!

Temporarily remove the matrix stuff, add a few print statements, and the code itself will tell you how the loops work! 临时删除矩阵内容,添加一些打印语句,代码本身将告诉您循环的工作方式!

n=4
for j in range (0,n):
    for i in range (n-1,n-j-2,-1):
        print(j, i)

Not sure if StackOverflow is the right platform for explaining the code. 不确定StackOverflow是否是解释代码的正确平台。 Anyways... 无论如何...

I changed the inner for loop to make it easy to understand 我更改了内部的for循环以使其易于理解

import numpy as np
n=4 

Create an n*n matrix 创建一个n * n矩阵

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

For each column in matrix 对于矩阵中的每一列

for j in range (0,n):

For each row in jth column, but from nj-1 to n-1 对于第j列中的每一行,但从nj-1到n-1

NOTE: In the original example, -1 at the end indicates reverse order. 注意:在原始示例中,末尾的-1表示相反的顺序。 I reversed the loop order and removed the -1 at the end, to produce the same output. 我颠倒了循环顺序,并在最后删除了-1 ,以产生相同的输出。 Please check to confirm 请检查确认

nj-1 : This should be understood by examples. nj-1:这应该通过示例来理解。 For j==0 the value is n-1 -> Last row. 对于j==0 ,值是n-1 >最后一行。 For the last column j==n-1 , the value is 0 -> First row. 对于最后一列j==n-1 ,值是0->第一行。 So for each column, starting from the last row, we proceed diagonally upward to the first row. 因此,对于每一列,从最后一行开始,我们对角向上进行到第一行。

Simply a logic/equation to move diagonally upward. 只需简单地将逻辑/方程对角向上移动即可。

NOTE: This is only the starting point for each column. 注意:这只是每列的起点。

n - 1 : Last row (though the second number is n, the call range(0, x) or range (x) expands from 0 to x - 1 . Much like array indexing) n-1:最后一行(尽管第二个数字是n,但调用range(0, x)range (x)0扩展到x - 1 。与数组索引非常相似)

    for i in range (n-j-1, n):
        matrix[i,j]=2*n-i-j-1 

print (matrix)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM