Y
Y
Yakov Feldman2018-04-27 21:07:58
Python
Yakov Feldman, 2018-04-27 21:07:58

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

3 answer(s)
I
Igor, 2018-04-27
@jfeldman

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))]

L
longclaps, 2018-04-27
@longclaps

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)))

Add commas to your liking.

B
blizzard, 2018-04-28
@s41blizzard

If I'm not mistaken, this question is similar to yours.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question