Reputation: 414
I imported a SQL table into a python list of lists and I would like to convert the format, in a kind of transpose manner, into a different format, where the key 'column' from the input table determines which elements are grouped in the output col. see example:
input list:
[
(1, 'eq510240'),
(1, 'eq510245'),
(1, 'eq510246'),
(2, 'eq510252'),
(2, 'eq510291'),
(3, 'eq510298')
]
desired output list:
[
('eq510240', 'eq510245', 'eq510246'),
('eq510252', 'eq510291'),
('eq510298')
]
Upvotes: 0
Views: 64
Reputation: 117926
You can use itertools.groupby
to group the elements by the first value of each tuple. Then in a list comprehension create a tuple
from the values in each group.
>>> from itertools import groupby
>>> [tuple(j[1] for j in g[1]) for g in groupby(l, key=lambda i: i[0])]
[('eq510240', 'eq510245', 'eq510246'),
('eq510252', 'eq510291'),
('eq510298',)]
Upvotes: 3