# How can I go from a list of sorted pairs to a list of pairs with a unique first element?

Given: there is a list of pairs sorted(sorted), the first element is the high key, the second element is the low key.

We need to get a list of pairs with a unique first element, so that all the second elements are glued together in a string - separated by commas - with the sorting preserved.

You can organize viewing and compression in a loop, you can - as a recursive function call.
• Add a question sheet and a sample result to the question. – Disney's88 Apr 27 '18 at 21:16

Almost like[[longclaps]], only in the form of hard-to-read list inclusion:
``````from itertools import groupby
from operator import itemgetter

lst=((0, 1),(0, 2),(1, 0),(2, 0),(2, 1),(2, 2))

result=[(i,','.join(str(j) for j in i)) for i in groupby(lst, itemgetter(0))]``````
the best solution is here
https://docs.python.org/2/library/collections.html

``````>>>s=[('yellow', 1),('blue', 2),('yellow', 3),('blue', 4),('red', 1)]
>>>d=defaultdict(list)
>>>for k, v in s:
...d[k] .append(v)
...
>>>d.items()
[('blue',[2, 4]),('red',),('yellow',[1, 3])]``````
• there is a list of sorted pairs (sorted)
``s=[('yellow', 1), ('blue', 2), ('yellow', 3 ), ('blue', 4), ('red', 1)]... [('blue', [2, 4]), ('red', ), ('yellow', [ 1, 3])]``

... while preserving sorts

It doesn’t matter what you mean - it’s important what you wrote down in the condition teacher.
– Muddy21 Apr 29 '18 at 12:04
Everything has already been invented before us, even the jig rolling machine was invented.
But in your case there is no finished tool(
We'll have to fence the bike:
``````from itertools import groupby
from operator import itemgetter

l=[(1, 1),(1, 2),(2, 1),(2, 3),(2, 5),(2, 7)]
for p, q in groupby(l, itemgetter(0)):
print(p, list(map(itemgetter(1), q)))``````