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

Duplicate element in list x amount of times based off another list

I have a list of numbers and a list of strings

a = ['2', '2', '3', '4']
b = [' ', 'A', 'B', 'C']

I want to duplicate each string in b a times making my output look like:

[' ', ' ', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C']

I’ve tried using map a bunch of different ways. Also would this be easier to do if I just switched the lists to numpy arrays and dealing it with that package.

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

>Solution :

You can use a list comprehension, you will need to cast the string-version of your numbers to integers though using map(int, a).

[z for x,y in zip(map(int,a), b) for z in x*y]
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