From the list of pairs sorted go to list of pairs with unique first element?

0 like 0 dislike
28 views
Given: there is a list of pairs sorted (sorted), the first element is a senior key, the second element of younger is the key.

It is necessary to obtain a list of pairs with unique first element, so that all second elements are stuck together in a string - comma-separated - preservation of sorts.

Can arrange viewing and compression in a loop as a recursive function call.
But there are no ready-made tools?
by | 28 views

4 Answers

0 like 0 dislike
Almost like longclaps, only a hard to read list include:
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))]
by
0 like 0 dislike
the best solution here
\rhttps://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', [1]), ('yellow', [1, 3])]
by
0 like 0 dislike
All is already invented to us, even gobusata machine invented.
But in your case a ready tool no (
Have city 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)))

Commas add yourself to taste.
by
0 like 0 dislike
If not mistaken, here is this question similar to yours
by

Related questions

0 like 0 dislike
1 answer
0 like 0 dislike
3 answers
0 like 0 dislike
1 answer
0 like 0 dislike
7 answers
0 like 0 dislike
1 answer
110,608 questions
257,186 answers
0 comments
33,730 users