-7

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

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

?

4

1 回答 1

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])]
于 2013-07-22T15:46:48.830 回答