So lets say I have 2 lists.
A = ['A', 'B', 'C']
B = [1, 2, 3, 4, 5]
As you can see, both lists are different lengths. Now I was wondering how I would make it so it iterates over both lists, but if list A has been fully iterated through, then iterate through List A again while still waiting for list B to be completed.
Example Output
A1
B2
C3
A4
B5
Not sure if this makes sense, if you want me to explain further I would be happy to do so.
Use itertools.cycle
Ex:
from itertools import cycle
A = cycle(['A', 'B', 'C'])
B = [1, 2, 3, 4, 5]
for k,v in zip(A,B):
print(f"{k}{v}")
Output:
A1
B2
C3
A4
B5
Try this
m, n = len(A), len(B)
for idx in range(max(m, n)):
print(f'{A[idx % m]}{B[idx % n]}')
Output:
A1
B2
C3
A4
B5
Try this,
A = ['A', 'B', 'C']
B = [1, 2, 3, 4, 5]
j=0
for i in B:
if j<len(A):
print(f'{A[j]}{i}')
j+=1
else:
j=0
print(f'{A[j]}{i}')
j+=1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.