简体   繁体   English

您如何使用范围 function 以在 for 循环中的每次迭代以 1 为增量从 0 计数到 8

[英]How do you use the range function to count from 0 to 8 by increments of 1 for each iteration in a for loop

I have a triple for loop that creates a 1 row and 2 column collection of numbers starting at 0 0 and going up to 2 2. The third for loop counts from 0 to 8. The code looks as follows:我有一个三重 for 循环,它创建一个从 0 0 到 2 2 的 1 行和 2 列数字集合。第三个 for 循环从 0 计数到 8。代码如下所示:

for N in range(0,3):
    for K in range(0,3):
        print(N,K)
        for P in range(0,9):
            print(P)

If you run this code you get the obvious output:如果你运行这段代码,你会得到明显的 output:

0 0
0
1
2
3
4
5
6
7
8
0 1
0
1
2
3
4
5
6
7
8
0 2
0 
1
2
3
4
5
6
7
8
...

And so on.等等。 I want instead of the output of 0 to 8 after the NK printout, instead something that looks like:在 NK 打印输出之后,我想要的不是 0 到 8 的 output,而是看起来像这样的东西:

0 0 
0
0 1
1
0 2
2
1 0
3
1 1
4
1 2
5
2 0
6
2 1
7
2 2
8

My first guess was an if statement that said:我的第一个猜测是一个 if 语句,它说:

if P == Q:
   break

where Q was several sets of sums and even the N,K array.其中 Q 是几组总和,甚至是 N,K 数组。 However, I couldn't figure out the best way to get my wanted output.但是,我想不出获得想要的 output 的最佳方法。 I do think an if statement is the best way to achieve my wanted result, but I'm not quite sure of how to approach it.我确实认为 if 语句是实现我想要的结果的最佳方式,但我不太确定如何处理它。 P is necessary for the rest of my code as it will be used in some subplots. P 对于我的代码的 rest 是必需的,因为它将在某些子图中使用。

As this is just an increment by one at each print, you can just do compute the index with N * 3 + K由于这只是每次打印时的增量,因此您可以使用N * 3 + K计算索引

for N in range(0, 3):
    for K in range(0, 3):
        print(N, K)
        print(N * 3 + K)

CODE DEMO

You can use zip to traverse two iterables in parallel.您可以使用zip并行遍历两个可迭代对象。 In this case, one of the iterables is the result of a nested list.在这种情况下,其中一个可迭代对象是嵌套列表的结果。 That can be handled by using itertools.product , as follows:这可以通过使用itertools.product来处理,如下所示:

import itertools

for (N, K), P in zip(itertools.product(range(3), range(3)), range(9)):
    print(N, K)
    print(P)

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

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