在python中合并元组

2024-09-30 04:40:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要合并以下数据:

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

我想要的输出是:

^{pr2}$

Tags: 数据sapetomhahahehepesapr2
2条回答
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()]

我想我明白他的意思。。。在

>>> 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']]

相关问题 更多 >

    热门问题