Enumerate the list of tuples

I would be very grateful for the contribution made to my question - it may not seem that it works. I need to iterate over the list of tuples, for example:

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

and would like to get the result, for example:

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

where I concatenate rows based on the second value in the tuple. I do not want to use groupbyout itertools, because although gconnected with 1, it is not immediately next to a. Thanks for all the answers!

+4
source share
2 answers

IIUC, you can use itertools.groupbyas it is grouped sequentially:

For instance:

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)]

Keyfunc for groupbygets the number from each tuple. Then for each group, you can combine the letters together using str.join.

+7

, groupby , a g. , , :

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

from collections import defaultdict
d = defaultdict(list)
for c,i in li:
  d[i].append(c)

new_li = [(''.join(cs), i) for (i, cs) in d.items()]

print(new_li)
# output: [('ag', 1), ('bcd', 2), ('ef', 3)]
+2

Source: https://habr.com/ru/post/1696083/


All Articles