Python元组列表将第二个元素与唯一的第一个元素合并

时间:2013-09-20 05:14:41

标签: python list merge tuples unique

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

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

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

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

谢谢,

5 个答案:

答案 0 :(得分: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)]

答案 1 :(得分: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)]

答案 2 :(得分:1)

这就是我提出的:

[tuple(list(el) + [q[1] for q in a if q[0]==el]) for el in set([q[0] for q in a])]

答案 3 :(得分: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)]

答案 4 :(得分:0)

一种方法是将列表理解表达式与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