-7

I have a simple list of strings:

1 test1
10 test1
2 test1
12 test2
87 test2
12 test1
75 test1
43 test1

How to get list of strings:

1+10+2 test1
12+87 test2
12+75+43 test1

?

Bdfy
  • 23,141
  • 55
  • 131
  • 179

1 Answers1

4

Use itertools.groupby() to group your numbers per test.. value:

from itertools import groupby

for key, group in groupby(list_of_strings, lambda k: k.split(None, 1)[-1]):
    # loop over `group` to see all strings that have the same last word.
    print '+'.join([s.split(None, 1)[0] for s in group]), key

group is an iterable that yields all contiguous strings that have the same second value (split on whitespace); your input has two test1 groups that are contiguous, for example.

Demo:

>>> list_of_strings = '''\
... 1 test1
... 10 test1
... 2 test1
... 12 test2
... 87 test2
... 12 test1
... 75 test1
... 43 test1
... '''.splitlines()
>>> from itertools import groupby
>>> for key, group in groupby(list_of_strings, lambda k: k.split(None, 1)[-1]):
...     # loop over `group` to see all strings that have the same last word.
...     print '+'.join([s.split(None, 1)[0] for s in group]), key
... 
1+10+2 test1
12+87 test2
12+75+43 test1

or, if you wanted to actually sum the values as integers:

for key, group in groupby(list_of_strings, lambda k: k.split(None, 1)[-1]):
    print sum(int(s.split(None, 1)[0]) for s in group), key

which prints

13 test1
99 test2
130 test1

If you just need the sums, make it a list comprehension:

sums = [sum(int(s.split(None, 1)[0]) for s in g) for _, g in groupby(L, lambda k: k.split(None, 1)[-1])]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343