Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over list of tuples

I would really appreciate some input on my question - can't seem to make it work. I need to iterate over a list of tuples such as:

li = [('a',1),('b',2),('c', 2),('d', 2), ('e', 3), ('f', 3), ('g', 1)]

and would like to get a result such as:

new_li = [('a', 1), ('bcd',2), ('ef',3), ('g',1)]

where I concatenate strings based on the second value in the tuple. I do not want to use groupby from itertools because even though g is associated with 1, it is not immediately next to a. Thank you for all of the responses!

like image 574
pythonista Avatar asked Dec 24 '22 08:12

pythonista


1 Answers

IIUC, you can use itertools.groupby as it groups sequentially:

For example:

from itertools import groupby
new_li = [
    ("".join(y[0] for y in g), x) for x, g in groupby(li, key=lambda x: x[1])
]
print(new_li)
#[('a', 1), ('bcd', 2), ('ef', 3), ('g', 1)]

The keyfunc for the groupby gets the number from each tuple. Then for each group, you can join the letters together using str.join.

like image 117
pault Avatar answered Jan 13 '23 02:01

pault