Home > Mobile >  Python inner loop and outer loop with counter to iterate over list
Python inner loop and outer loop with counter to iterate over list

Time:06-30

I have specific issue where, im trying to find solution on inner loop(execute 3 time) and continue outer to process rest of the list in for loop:

strings = ['A','A','A','A','A','A','A','A','A','A','B','B','B','B','B','B','B','B','B','B',\
           'A','A','A','A','A','A','A','A','A','A','B','B','B','B','B','B','B','B','B','B']

i=0
for string in strings:
    global i
    if string == 'A':
        while i < 3:
            print(string, i)
            i =1
            if i==3: continue
    elif string== 'B':
         while i < 3:
            print(string,i)
            i =1
            if i==3: continue
#         print(string)

Current result: A 0 A 1 A 2

Expected to have continued over list once the inner loop complete and process from next:

A 0
A 1
A 2

B 0
B 1
B 2

A 0
A 1
A 2

B 0
B 1
B 2

CodePudding user response:

If I understand correctly the logic, you could use itertools.groupby to help you form the groups:

variant #1

from itertools import groupby

MAX = 3

for k,g in groupby(strings):
    for i in range(min(len(list(g)), MAX)):
        print(f'{k} {i}')
    print()

variant #2

from itertools import groupby

MAX = 3

for k,g in groupby(strings):
    for i,_ in enumerate(g):
        if i >= MAX:
            break
        print(f'{k} {i}')
    print()

output:

A 0
A 1
A 2

B 0
B 1
B 2

A 0
A 1
A 2

B 0
B 1
B 2

variant #3: without import

prev = None
count = 0
MAX = 3
for s in strings:
    if s == prev:
        if count < MAX:
            print(f'{s} {count}')
            count  = 1
    elif prev:
        count = 0
        print()
    prev = s
  • Related