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,
解决方案
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)]