简体   繁体   中英

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 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:

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:

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 P == Q:
   break

where Q was several sets of sums and even the N,K array. However, I couldn't figure out the best way to get my wanted 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. P is necessary for the rest of my code as it will be used in some subplots.

As this is just an increment by one at each print, you can just do compute the index with 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. In this case, one of the iterables is the result of a nested list. That can be handled by using itertools.product , as follows:

import itertools

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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