我有一个简单的字符串列表:
1 test1
10 test1
2 test1
12 test2
87 test2
12 test1
75 test1
43 test1
如何获取字符串列表:
1+10+2 test1
12+87 test2
12+75+43 test1
答案 0 :(得分:4)
使用itertools.groupby()
按test..
值对数字进行分组:
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
是一个可迭代的,它产生具有相同第二个值的所有连续字符串(在空格上拆分);例如,您的输入有两个连续的test1
组。
演示:
>>> 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
或者,如果您想要将值实际求和为整数:
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
打印
13 test1
99 test2
130 test1
如果您只需要总和,请将其列为清单:
sums = [sum(int(s.split(None, 1)[0]) for s in g) for _, g in groupby(L, lambda k: k.split(None, 1)[-1])]