Home > Mobile >  python nested for loop when index of outer loop equals to length of inner loop you start again
python nested for loop when index of outer loop equals to length of inner loop you start again

Time:05-05

I have

A = ['A','B','C','D','E','F','G','H']
B= ['a','b']

want to iterate through the list to get

C = ['Aa','Bb','Ca','Db','Ea','Fb','Ga','Hb']

how can I go about it in python

CodePudding user response:

You can use a list comprehension :

a = ['A','B','C','D','E','F','G','H']
b = ['a','b']

c = [a[i]   b[i%2] for i in range(len(a))]

# ['Aa', 'Bb', 'Ca', 'Db', 'Ea', 'Fb', 'Ga', 'Hb']

CodePudding user response:

You can use zip() and cycle():

from itertools import cycle

A = ['A','B','C','D','E','F','G','H']
B = ['a', 'b']

C = [a   b for a,b in zip(A, cycle(B))]
print(C)

Output as requested.

CodePudding user response:

You can do this by using the index in the A list mapped on the number of elements in the B list with the modulo operation (%) :

A = [1,2,3,4,5,6,7,8]
B= ['a','b']
C = []

for i in range(len(A)):
    C.append(f"{A[i]}{B[i%2]}")

CodePudding user response:

More variations:

from itertools import cycle
from operator import add

A = ['A','B','C','D','E','F','G','H']
B = ['a','b']
E = ['Aa','Bb','Ca','Db','Ea','Fb','Ga','Hb']

C = list(map(add, A, cycle(B)))
print(C == E)

C = [a   B[i%2] for i, a in enumerate(A)]
print(C == E)

C = list(map(''.join, zip(A, cycle(B))))
print(C == E)

C = list(map('{}{}'.format, A, cycle(B)))
print(C == E)

CodePudding user response:

You can also try this:

A = ['A','B','C','D','E','F','G','H']
B= ['a','b']
LB = len(B)
x = 0

for i in A :
    if x>=LB :
        x=0
    print(i B[x])
    x =1

CodePudding user response:

A = [1, 2, 3, 4, 5, 6, 7, 8]
B = ["a", "b", "c", "d", "f", "g", "h", "q"]
C = []
i = 0
while i < len(A):
    for j in B:
        C.append("{}{}".format(A[i], j))   
    i = i   1
        

print(C)

You can try this without any module.

You can specify your arrays, works anyway. I just tested like this.

  • Related