5

给定一个像这样的元组列表:

a = [ ( "x", 1, ), ( "x", 2, ), ( "y", 1, ), ( "y", 3, ), ( "y", 4, ) ]

过滤唯一的第一个元素并合并第二个元素的最简单方法是什么。需要这样的输出。

b = [ ( "x", 1, 2 ), ( "y", 1, 3, 4 ) ]

谢谢,

4

5 回答 5

5
>>> a = [("x", 1,), ("x", 2,), ("y", 1,), ("y", 3,), ("y", 4,)]
>>> d = {}
>>> for k, v in a:
...     d.setdefault(k, [k]).append(v)
>>> b = map(tuple, d.values())
>>> b
[('y', 1, 3, 4), ('x', 1, 2)]
于 2013-09-20T05:38:48.867 回答
2

您可以使用defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(tuple)
>>> a = [('x', 1), ('x', 2), ('y', 1), ('y', 3), ('y', 4)]
>>> for tup in a:
...     d[tup[0]] += (tup[1],)
...
>>> [tuple(x for y in i for x in y) for i in d.items()]
[('y', 1, 3, 4), ('x', 1, 2)]
于 2013-09-20T05:21:22.963 回答
1

这就是我想出的:

[tuple(list(el) + [q[1] for q in a if q[0]==el]) for el in set([q[0] for q in a])]
于 2013-09-20T05:24:01.427 回答
0

除了以前的答案,另一个单行:

>>> a = [ ( "x", 1, ), ( "x", 2, ), ( "y", 1, ), ( "y", 3, ), ( "y", 4, ) ]
>>> from itertools import groupby
>>> [(key,) + tuple(elem for _, elem in group) for key, group in groupby(a, lambda pair: pair[0])]
[('x', 1, 2), ('y', 1, 3, 4)]
于 2013-09-20T05:29:46.180 回答
0

一种方法是使用带有,和as的列表理解表达式:itertools.groupbyitertools.chainoperator.itemgetter

>>> from itertools import groupby, chain
>>> from operator import itemgetter

>>> my_list = [ ( "x", 1, ), ( "x", 2, ), ( "y", 1, ), ( "y", 3, ), ( "y", 4, ) ]

>>> [set(chain(*i)) for _, i in groupby(sorted(my_list), key=itemgetter(0))]
[set(['x', 2, 1]), set(['y', 1, 3, 4])]

注意: set本质上是无序的,因此它们不会保留元素的位置。set如果位置很重要,请勿使用。

于 2017-11-18T21:01:30.370 回答