简体   繁体   English

为什么嵌套 for 循环的这个 Python 会产生我得到的 output?

[英]Why does this Python nested for loop produce the output I get?

I'm very new to learning python, though I understand the basics of the looping, I am unable to understand the method in which output is arrived at.我对学习 python 很陌生,虽然我了解循环的基础知识,但我无法理解 output 的方法。

In particular, how does the mapping of all three for loops happen to give the desired output, as I finding it impossible to understand the logic to be applied, when I try to write the output on paper without referring to IDE.特别是,当我尝试在纸上写 output 而不参考 Z581D6387203F35E7B394ACD7 时,我发现无法理解要应用的逻辑,因此所有三个 for 循环的映射如何恰好给出所需的 output。

Code:代码:

n = 4
a = 3
z = 2
for i in range(n):
    for j in range(a):
        for p in range(z):
            print(i, j, p)

Output is: Output 是:

0 0 0
0 0 1
0 1 0
0 1 1
0 2 0
0 2 1
1 0 0
1 0 1
1 1 0
1 1 1
1 2 0
1 2 1
2 0 0
2 0 1
2 1 0
2 1 1
2 2 0
2 2 1
3 0 0
3 0 1
3 1 0
3 1 1
3 2 0
3 2 1

The first loop iterates four times.第一个循环迭代四次。

The second loop iterates three times.第二个循环迭代三次。 However since it is embedded inside the first loop, it actually iterates twelve times (4 * 3.)然而,由于它嵌入在第一个循环中,它实际上迭代了 12 次 (4 * 3.)

The third loop iterates two times.第三个循环迭代两次。 However since it is embedded inside the first and second loops, it actually iterates twenty-four times (4 * 3 * 2).然而,由于它嵌入在第一个和第二个循环中,它实际上迭代了 24 次 (4 * 3 * 2)。

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

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