Home > OS >  Python Sequential parallel loop gets stuck in the middle
Python Sequential parallel loop gets stuck in the middle

Time:11-24

I'm making a sequential parallel loop. It runs for the first time, but ends without running the loop. I don't know which part is wrong.

Running the code the value is

[2, 3, 3] [2, 2, 3] [2, 2, 2]

If I replace it with while statement, I can't get the value I want.

[2, 3, 3] [1, 3, 3] [0, 3, 3] [0, 2, 3] [0, 1, 3] [0, 0, 3] [0, 0, 2] [0, 0, 1] [0, 0, 0] This is an invalid value.

the value i want is

[2, 3, 3] [2, 2, 3] [2, 2, 2] [1, 2, 2] [1, 1, 2] [1, 1, 1] [0, 1, 1] [0, 0, 1] [0, 0, 0] is the value.

import time

list_a = ['AA','BB','CC']
list_b = ['AAdata','BBdata','CCdata']
dd = 'state'

retry_cnt = [3] * len(list_a) 
for i, symbol in enumerate(list_b):
    if retry_cnt[i] > 0:
        dd = 'state'
        time.sleep(0.2)
        if 'state' in dd:
            retry_cnt[i] -= 1
            time.sleep(0.2)
            print(retry_cnt)     
            continue   
    

CodePudding user response:

Your loop is only executing 3 times because list_b only has 3 elements in it.

If you want the whole loop to run 3 times, you could wrap it in another for loop, like so:

for x in range(3):
    for i, symbol in enumerate(list_b):
        if retry_cnt[i] > 0:
            dd = 'state'
            time.sleep(0.2)
            if 'state' in dd:
                retry_cnt[i] -= 1
                time.sleep(0.2)
                print(retry_cnt)     

Also, the continue is probably unnecessary because it is the last instruction in the loop, so it happens automatically.

  • Related