AugBar AugBar - 4 months ago 27
Python Question

Pythonic way to generate a list of list

What would be the most pythonic way of achieving the transformation from the following input:

input = [('a', 1), ('a', 10), ('b', 244), ('c', 31) , ('c',45)]

to the desired output:

output = [[('a',1),('a',10)],[('c',31),('c',45)]]

where I have grouped in lists the tuples which have the same first element.

Feeling that Python has a strong potential (I'm new with it) in writing complicated things on one line, I have decided to use comprehensive lists. My initial try is something like:

output = [x for x in input if [k[0] for f in input].count(x[0])>1]

giving me a nice list of all my "pseudo" duplicates :

output = [('a',1),('a',10),('c',31),('c',45)]

which I further process to obtain my result.

My question is: is there a way to achieve this result in one line using comprehensive lists instead of two (ugly) steps?


Use groupby from itertools and list comprehension. This will give you a simple one liner:

from itertools import groupby

filter(lambda x: len(x)>1, [list(g) for i,g in groupby(input, key=lambda x: x[0])])
[[('a', 1), ('a', 10)], [('c', 31), ('c', 45)]]