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!
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With