Home > Software engineering >  Grouping two elements at a time
Grouping two elements at a time

Time:04-19

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:

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

CodePudding user response:

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