I have a list
A = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
and another list,
B = [‘c’, ‘a’, ‘t’]
I want a script to get result like
C = [‘c’, ‘a’, ‘t’, ‘c’, ‘a’]
Pls help or give some idea how to achieve it. Thank you in advance pls help.
>Solution :
The logic is unclear, but assuming that you want to repeat the items of B as many times as needed to match the length of A, use itertools.cycle and itertools.islice:
from itertools import cycle, islice
A = ['a', 'b', 'c', 'd', 'e']
B = ['c', 'a', 't']
C = list(islice(cycle(B), len(A)))
Output: ['c', 'a', 't', 'c', 'a']
For fun, another (less efficient) approach but without imports, repeating, then slicing A:
C = (B*-(-len(A)//len(B)))[:len(A)]
# -(-len(A)//len(B)) is a trick to get the ceiled value of len(A)/len(B)
combining A and B
from itertools import cycle
C = [''.join(x) for x in zip(A, cycle(B))]
Output: ['ac', 'ba', 'ct', 'dc', 'ea']