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

Merge python list by specific indexes

I have an array, where I want a specific index to be merged.

["captain:", "robot", "alpha", "beta:", "gama", "delta:", "fighter", "test", "exp"]

the idea of this, every even element should contain : and the rest of the elements should not contain :

The output I want:

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

["captain:", "robot, alpha", "beta:", "gama", "delta:", "fighter, test, exp"]

considering the array is changeable, for example, the array could be:

["captain:", "robot", "beta:", "game", "exp", "delta:", "fighter", "test"]

the output should be the same, each even with : and odd index without :

Can anyone help, please?

>Solution :

Here’s an implementation using groupby:

import itertools
x = ["captain:", "robot", "alpha", "beta:", "gama", "delta:", "fighter", "test", "exp"]
new_list = []
for key, group in itertools.groupby(x, key = lambda string: string.endswith(':')):
    if key: # in case you happen to consecutive values that end in a colon
        new_list += list(group)
    else: # these elements do not end in a colon
        new_list.append(', '.join(group))
print(new_list)
# ['captain:', 'robot, alpha', 'beta:', 'gama', 'delta:', 'fighter, test, exp']

Here, the grouping key checks to see if the item ends in a ":", if it does, key is True, otherwise it is False. If consecutive values of key are the same, they are put in the same group. Thus, any number of elements following a string containing a colon will be grouped together.

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