user 1987 user 1987 - 27 days ago 11
Python Question

list of duplicates on python

If I have a list, how do I create from it a list of lists of duplicates?
For instance, if I have the list

L = [1,2,1,3,4,2,1,4]


I want the output to be

L1 = [[1,1,1], [2,2], [3], [4,4]]

Answer

There must be about a hundred ways of doing this. Here's one. If you want more, since this is really a Python question add the Python tag to your question.

>>> L = [1,2,1,3,4,2,1,4]
>>> from collections import Counter
>>> counts = Counter(L)
>>> counts
Counter({1: 3, 2: 2, 4: 2, 3: 1})
>>> L1 = [ [ _ ]*counts[_] for _ in counts.keys() ]
>>> L1
[[1, 1, 1], [2, 2], [3], [4, 4]]