如何在列表中对重复值进行求和?

时间:2013-07-22 15:42:48

标签: python

我有一个简单的字符串列表:

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

1 个答案:

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