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

Grouping two elements at a time

I have a list of data and I need to perform a grouping operation two elements at a time. I tried to making it myself, but it takes too much time. I have a large list, so I need a faster way.

Here is an example input:

lst = [["title1","content1"],["title2","content2"],["title3","content3"],["title4","content4"],["title5","content5"]]

and here is an example output:

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

lst = [["title1","content1 content2"]["title3","content3 content4"],["title5","content5"]]

>Solution :

You can use zip_longest() to handle two elements at a time:

from itertools import zip_longest
result = [[first, ' '.join([second, fourth])] if fourth is not None else [first, second]
    for (first, second), (_, fourth) in zip_longest(lst[0::2], lst[1::2], fillvalue=(None, None))]

This outputs:

[['title1', 'content1 content2'], ['title3', 'content3 content4'], ['title5', 'content5']]
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