Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list of tuples merge 2nd element with unique first element

Given a list of tuples like so:

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

What would be the easiest way to filter for unique first element and merge the second element. An output like so would be desired.

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

Thanks,

like image 874
chuy08 Avatar asked Sep 20 '13 05:09

chuy08


2 Answers

>>> 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)]
like image 96
Roman Pekar Avatar answered Nov 15 '22 09:11

Roman Pekar


You can use a 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)]
like image 28
TerryA Avatar answered Nov 15 '22 08:11

TerryA