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

List combination based on value of each index in another list

I have the following two lists

list_1 = [3, 5, 7, 2]

list_2 = [
          '1-CHA', '2-NOF', '3-INC',
          '4-CHA', '5-NOF', '6-NOF', '7-INC', '8-INC',
          '9-INC', '10-INC', '11-CHA', '12-NOF', '13-CHA', '14-CHA', '15-INC', 
          '16-INC', '17-INC'
         ]

I want to combine the two lists in the following way:

final_list = [
              '1-CHA|2-NOF|3-INC',
              '4-CHA|5-NOF|6-NOF|7-INC|8-INC',
              '9-INC|10-INC|11-CHA|12-NOF|13-CHA|14-CHA|15-INC',
              '16-INC|17-INC'
             ]

final_list – should have the same length as list_1

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 create an iterator from list_2 so that you can fetch items from the list for the number of times specified in list_1 by calling next on the iterator:

seq = iter(list_2)
final_list = ['|'.join(next(seq) for _ in range(n)) for n in list_1]

Demo: https://replit.com/@blhsing/BlandEssentialJavadoc

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