Home > other >  Python loop compare two loop output
Python loop compare two loop output

Time:09-28

for i in range(10):
    pass

for s in range(10):
    print(s,i)

This is my code and output is

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

How to get

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

I need to compare two loop outputs , What is best way? when i try to this way i loop not working

CodePudding user response:

If you have two loops that are producing an output that you are trying to compare side by side (as indicated by your comments). Then without knowing more about the specifics of your problem, I suppose this generic solution will work

loop_a = []
loop_b = []

for i in range(10):
    # Calculate result, this is a dummy version
    result = i
    # Save it to an array
    loop_a.append(result)
    

for i in range(10):
    # Calculate result, this is a dummy version
    result = i
    # Save it to an array
    loop_b.append(result)

for a, b in zip(loop_a, loop_b):
    print(a, b)
    

CodePudding user response:

Your example is a bit weird as you are using simple ranges, but I assume this is only an example and you might have a more complex generator.

You could use iterators and a single loop:

I = iter(range(10)) # this is just a dummy example
S = iter(range(10))

for i in range(10):
    print(next(S), next(I))

or a more fancy version where you do not need to know the size of the iterators:

I = iter(range(10))
S = iter(range(10))

while True:
    try:
        print(next(S), next(I))
    except StopIteration:
        break

output:

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

CodePudding user response:

In your code, the first for loop reaches the end which makes the value of i=9; and when you are looping through the second "for" loop you're basically printing the same value for "i" while "s" is looping, hence the output. I'd suggest appending your results to an array and printing them after iterating through the for loops.

  • Related