Join strings from consecutive equal tuples

Viewed 82

Given a list which looks like this:

[(1, 'a'), (1, 'b'), (2, 'c'), (1, 'd')]

I want to join the consecutive tuples inside the list if they have same first value, so the result looks like following:

[(1, 'ab'), (2, 'c'), (1, 'd')]

Should only join if both are next to each other.

If key is None like below it should be merged to previous item.

[(1, 'a'), (1, 'b'), (None, 'e'), (2, 'c'), (1, 'd')]

result should be

[(1, 'abe'), (2, 'c'), (1, 'd')]
1 Answers

You can use itertools.groupby to group consecutive sublists with the same first value, and join the strings from the corresponding gruoped tuples:

from itertools import groupby
l = [(1, 'a'), (1, 'b'), (2, 'c'), (1, 'd')]

[(k,''.join([i for _,i in v])) for k,v in groupby(l, key=lambda x:x[0])]
# [(1, 'ab'), (2, 'c'), (1, 'd')]
Related