Answer the question
In order to leave comments, you need to log in
How to go from a sorted list of pairs to a list of pairs with a unique first element?
Given: there is a sorted list of pairs, the first element is the high key, the second element is the low key.
It is necessary to get a list of pairs with a unique first element, so that all the second elements are glued into a string - separated by commas - with sorting preserved.
You can organize viewing and compression in a cycle, you can - as a recursive function call.
But are there ready-made tools here?
Answer the question
In order to leave comments, you need to log in
Almost like longclaps , only in the form of a 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[0], ', '.join(str(j[1]) for j in i[1])) for i in groupby(lst, itemgetter(0))]
Everything has already been invented before us, even the lip-rolling machine has been invented.
But in your case, there is no ready-made 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)))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question