-4

我有以下需要合并的数据:

tuples = ('ziyao','sa'),('guilog','sa'),('yiping','pe'),('tom','pesa'),('haha','pesa'),('hehe','pesa')

我想要的输出是:

tuples = [('ziyao','guilog','sa'),('yiping','pe'),('tom','haha','hehe','pesa')] # or 'ziyao','guilog','sa'\n'yiping','pe'\n...
4

2 回答 2

4

我想我明白他的意思了...

>>> from itertools import groupby
>>> tuples = ('ziyao','sa'),('guilog','sa'),('yiping','pe'),('tom','pesa'),('haha','pesa'),('hehe','pesa')
>>> [list(zip(*v)[0]) + [k] for k,v in groupby(tuples,lambda x: x[1])]
[['ziyao', 'guilog', 'sa'], ['yiping', 'pe'], ['tom', 'haha', 'hehe', 'pesa']]
于 2012-04-06T05:33:02.853 回答
1
from collections import defaultdict
by_second = defaultdict(list)
for first, second in input_tuples:
    by_second[second].append(first)
output_tuples = [tuple(v) + (k,) for k,v in by_second.iteritems()]
于 2012-04-06T04:59:10.070 回答