我需要合并以下数据:
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...
答案 0 :(得分: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']]
答案 1 :(得分: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()]