Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing one list with other

I have a list

A = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

and another list,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading