0

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')
]
1
  • 1
    Can you please show your attempt? Can you provide an minimal reproducible example of your attempt? Did you get an error? Commented Aug 31, 2017 at 13:28

1 Answer 1

3

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',)]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.