Home > database >  Skip particular repetition in nested foor loop - Python
Skip particular repetition in nested foor loop - Python

Time:04-08

for k in range(8):
    for i in range(2): #number of columns
        for j in range(4): #number of row
            print(k,j,i)

I want an output like this. no repetition of first for loop

k,j,i
-----
0 0 0
1 1 0
2 2 0
3 3 0
4 0 1
5 1 1 
6 2 1
7 3 1

How I will achieve this?

CodePudding user response:

Normally i would do

for i in range(8):
    print(i, i%4, i%2)

Output:

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

But to reproduce your exact output:

for i in range(8):
    print(i, i%4, int(i>3))

Output:

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

CodePudding user response:

You can use if statements to say things like if k == 7 or something along those lines. This will only allow it to loop the first loop before moving on to the second loop.

CodePudding user response:

Other answers have shown similar ways to produce your exact output, but this is another way to do it, and this would still work if you wanted the number of rows to be more than 8 and you wanted i to keep increasing

for i in range(8):
    print(i, i%4, i//4)

I hope this is useful, sorry if it isn't

CodePudding user response:

Looking at i and j, you have the cartesian product of {0,1} and {0,1,2,3}. You can compute that with itertools.product(range(2), range(4)), then use enumerate to number them for your k value.

from itertools import product


for k, (i, j) in enumerate(product(range(2), range(4))):
    print(k, j, i)

Earlier arguments to product vary more slowly than later arguments.

  • Related